• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2014 Google Inc. All rights reserved.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 // independent from idl_parser, since this code is not needed for most clients
18 
19 #include "flatbuffers/flatbuffers.h"
20 #include "flatbuffers/flexbuffers.h"
21 #include "flatbuffers/idl.h"
22 #include "flatbuffers/util.h"
23 
24 namespace flatbuffers {
25 
26 static bool GenStruct(const StructDef &struct_def, const Table *table,
27                       int indent, const IDLOptions &opts, std::string *_text);
28 
29 // If indentation is less than 0, that indicates we don't want any newlines
30 // either.
NewLine(const IDLOptions & opts)31 const char *NewLine(const IDLOptions &opts) {
32   return opts.indent_step >= 0 ? "\n" : "";
33 }
34 
Indent(const IDLOptions & opts)35 int Indent(const IDLOptions &opts) { return std::max(opts.indent_step, 0); }
36 
37 // Output an identifier with or without quotes depending on strictness.
OutputIdentifier(const std::string & name,const IDLOptions & opts,std::string * _text)38 void OutputIdentifier(const std::string &name, const IDLOptions &opts,
39                       std::string *_text) {
40   std::string &text = *_text;
41   if (opts.strict_json) text += "\"";
42   text += name;
43   if (opts.strict_json) text += "\"";
44 }
45 
46 // Print (and its template specialization below for pointers) generate text
47 // for a single FlatBuffer value into JSON format.
48 // The general case for scalars:
49 template<typename T>
Print(T val,Type type,int,Type *,const IDLOptions & opts,std::string * _text)50 bool Print(T val, Type type, int /*indent*/, Type * /*union_type*/,
51            const IDLOptions &opts, std::string *_text) {
52   std::string &text = *_text;
53   if (type.enum_def && opts.output_enum_identifiers) {
54     auto enum_val = type.enum_def->ReverseLookup(static_cast<int64_t>(val));
55     if (enum_val) {
56       text += "\"";
57       text += enum_val->name;
58       text += "\"";
59       return true;
60     }
61   }
62 
63   if (type.base_type == BASE_TYPE_BOOL) {
64     text += val != 0 ? "true" : "false";
65   } else {
66     text += NumToString(val);
67   }
68 
69   return true;
70 }
71 
72 // Print a vector a sequence of JSON values, comma separated, wrapped in "[]".
73 template<typename T>
PrintVector(const Vector<T> & v,Type type,int indent,const IDLOptions & opts,std::string * _text)74 bool PrintVector(const Vector<T> &v, Type type, int indent,
75                  const IDLOptions &opts, std::string *_text) {
76   std::string &text = *_text;
77   text += "[";
78   text += NewLine(opts);
79   for (uoffset_t i = 0; i < v.size(); i++) {
80     if (i) {
81       if (!opts.protobuf_ascii_alike) text += ",";
82       text += NewLine(opts);
83     }
84     text.append(indent + Indent(opts), ' ');
85     if (IsStruct(type)) {
86       if (!Print(v.GetStructFromOffset(i * type.struct_def->bytesize), type,
87                  indent + Indent(opts), nullptr, opts, _text)) {
88         return false;
89       }
90     } else {
91       if (!Print(v[i], type, indent + Indent(opts), nullptr, opts, _text)) {
92         return false;
93       }
94     }
95   }
96   text += NewLine(opts);
97   text.append(indent, ' ');
98   text += "]";
99   return true;
100 }
101 
102 // Specialization of Print above for pointer types.
103 template<>
Print(const void * val,Type type,int indent,Type * union_type,const IDLOptions & opts,std::string * _text)104 bool Print<const void *>(const void *val, Type type, int indent,
105                          Type *union_type, const IDLOptions &opts,
106                          std::string *_text) {
107   switch (type.base_type) {
108     case BASE_TYPE_UNION:
109       // If this assert hits, you have an corrupt buffer, a union type field
110       // was not present or was out of range.
111       FLATBUFFERS_ASSERT(union_type);
112       return Print<const void *>(val, *union_type, indent, nullptr, opts,
113                                  _text);
114     case BASE_TYPE_STRUCT:
115       if (!GenStruct(*type.struct_def, reinterpret_cast<const Table *>(val),
116                      indent, opts, _text)) {
117         return false;
118       }
119       break;
120     case BASE_TYPE_STRING: {
121       auto s = reinterpret_cast<const String *>(val);
122       if (!EscapeString(s->c_str(), s->size(), _text, opts.allow_non_utf8,
123                         opts.natural_utf8)) {
124         return false;
125       }
126       break;
127     }
128     case BASE_TYPE_VECTOR:
129       type = type.VectorType();
130       // Call PrintVector above specifically for each element type:
131       switch (type.base_type) {
132         // clang-format off
133         #define FLATBUFFERS_TD(ENUM, IDLTYPE, \
134           CTYPE, JTYPE, GTYPE, NTYPE, PTYPE, RTYPE) \
135           case BASE_TYPE_ ## ENUM: \
136             if (!PrintVector<CTYPE>( \
137                   *reinterpret_cast<const Vector<CTYPE> *>(val), \
138                   type, indent, opts, _text)) { \
139               return false; \
140             } \
141             break;
142           FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
143         #undef FLATBUFFERS_TD
144         // clang-format on
145       }
146       break;
147     default: FLATBUFFERS_ASSERT(0);
148   }
149   return true;
150 }
151 
GetFieldDefault(const FieldDef & fd)152 template<typename T> static T GetFieldDefault(const FieldDef &fd) {
153   T val;
154   auto check = StringToNumber(fd.value.constant.c_str(), &val);
155   (void)check;
156   FLATBUFFERS_ASSERT(check);
157   return val;
158 }
159 
160 // Generate text for a scalar field.
161 template<typename T>
GenField(const FieldDef & fd,const Table * table,bool fixed,const IDLOptions & opts,int indent,std::string * _text)162 static bool GenField(const FieldDef &fd, const Table *table, bool fixed,
163                      const IDLOptions &opts, int indent, std::string *_text) {
164   return Print(
165       fixed ? reinterpret_cast<const Struct *>(table)->GetField<T>(
166                   fd.value.offset)
167             : table->GetField<T>(fd.value.offset, GetFieldDefault<T>(fd)),
168       fd.value.type, indent, nullptr, opts, _text);
169 }
170 
171 static bool GenStruct(const StructDef &struct_def, const Table *table,
172                       int indent, const IDLOptions &opts, std::string *_text);
173 
174 // Generate text for non-scalar field.
GenFieldOffset(const FieldDef & fd,const Table * table,bool fixed,int indent,Type * union_type,const IDLOptions & opts,std::string * _text)175 static bool GenFieldOffset(const FieldDef &fd, const Table *table, bool fixed,
176                            int indent, Type *union_type, const IDLOptions &opts,
177                            std::string *_text) {
178   const void *val = nullptr;
179   if (fixed) {
180     // The only non-scalar fields in structs are structs.
181     FLATBUFFERS_ASSERT(IsStruct(fd.value.type));
182     val = reinterpret_cast<const Struct *>(table)->GetStruct<const void *>(
183         fd.value.offset);
184   } else if (fd.flexbuffer) {
185     auto vec = table->GetPointer<const Vector<uint8_t> *>(fd.value.offset);
186     auto root = flexbuffers::GetRoot(vec->data(), vec->size());
187     root.ToString(true, opts.strict_json, *_text);
188     return true;
189   } else if (fd.nested_flatbuffer) {
190     auto vec = table->GetPointer<const Vector<uint8_t> *>(fd.value.offset);
191     auto root = GetRoot<Table>(vec->data());
192     return GenStruct(*fd.nested_flatbuffer, root, indent, opts, _text);
193   } else {
194     val = IsStruct(fd.value.type)
195               ? table->GetStruct<const void *>(fd.value.offset)
196               : table->GetPointer<const void *>(fd.value.offset);
197   }
198   return Print(val, fd.value.type, indent, union_type, opts, _text);
199 }
200 
201 // Generate text for a struct or table, values separated by commas, indented,
202 // and bracketed by "{}"
GenStruct(const StructDef & struct_def,const Table * table,int indent,const IDLOptions & opts,std::string * _text)203 static bool GenStruct(const StructDef &struct_def, const Table *table,
204                       int indent, const IDLOptions &opts, std::string *_text) {
205   std::string &text = *_text;
206   text += "{";
207   int fieldout = 0;
208   Type *union_type = nullptr;
209   for (auto it = struct_def.fields.vec.begin();
210        it != struct_def.fields.vec.end(); ++it) {
211     FieldDef &fd = **it;
212     auto is_present = struct_def.fixed || table->CheckField(fd.value.offset);
213     auto output_anyway = opts.output_default_scalars_in_json &&
214                          IsScalar(fd.value.type.base_type) && !fd.deprecated;
215     if (is_present || output_anyway) {
216       if (fieldout++) {
217         if (!opts.protobuf_ascii_alike) text += ",";
218       }
219       text += NewLine(opts);
220       text.append(indent + Indent(opts), ' ');
221       OutputIdentifier(fd.name, opts, _text);
222       if (!opts.protobuf_ascii_alike ||
223           (fd.value.type.base_type != BASE_TYPE_STRUCT &&
224            fd.value.type.base_type != BASE_TYPE_VECTOR))
225         text += ":";
226       text += " ";
227       switch (fd.value.type.base_type) {
228           // clang-format off
229           #define FLATBUFFERS_TD(ENUM, IDLTYPE, \
230             CTYPE, JTYPE, GTYPE, NTYPE, PTYPE, RTYPE) \
231             case BASE_TYPE_ ## ENUM: \
232               if (!GenField<CTYPE>(fd, table, struct_def.fixed, \
233                                    opts, indent + Indent(opts), _text)) { \
234                 return false; \
235               } \
236               break;
237           FLATBUFFERS_GEN_TYPES_SCALAR(FLATBUFFERS_TD)
238         #undef FLATBUFFERS_TD
239         // Generate drop-thru case statements for all pointer types:
240         #define FLATBUFFERS_TD(ENUM, IDLTYPE, \
241           CTYPE, JTYPE, GTYPE, NTYPE, PTYPE, RTYPE) \
242           case BASE_TYPE_ ## ENUM:
243           FLATBUFFERS_GEN_TYPES_POINTER(FLATBUFFERS_TD)
244         #undef FLATBUFFERS_TD
245             if (!GenFieldOffset(fd, table, struct_def.fixed, indent + Indent(opts),
246                                 union_type, opts, _text)) {
247               return false;
248             }
249             break;
250           // clang-format on
251       }
252       if (fd.value.type.base_type == BASE_TYPE_UTYPE) {
253         auto enum_val = fd.value.type.enum_def->ReverseLookup(
254             table->GetField<uint8_t>(fd.value.offset, 0));
255         union_type = enum_val ? &enum_val->union_type : nullptr;
256       }
257     }
258   }
259   text += NewLine(opts);
260   text.append(indent, ' ');
261   text += "}";
262   return true;
263 }
264 
265 // Generate a text representation of a flatbuffer in JSON format.
GenerateTextFromTable(const Parser & parser,const void * table,const std::string & table_name,std::string * _text)266 bool GenerateTextFromTable(const Parser &parser, const void *table,
267                            const std::string &table_name, std::string *_text) {
268   auto struct_def = parser.LookupStruct(table_name);
269   if (struct_def == nullptr) {
270     return false;
271   }
272   auto text = *_text;
273   text.reserve(1024);  // Reduce amount of inevitable reallocs.
274   auto root = static_cast<const Table *>(table);
275   if (!GenStruct(*struct_def, root, 0, parser.opts, _text)) {
276     return false;
277   }
278   text += NewLine(parser.opts);
279   return true;
280 }
281 
282 // Generate a text representation of a flatbuffer in JSON format.
GenerateText(const Parser & parser,const void * flatbuffer,std::string * _text)283 bool GenerateText(const Parser &parser, const void *flatbuffer,
284                   std::string *_text) {
285   std::string &text = *_text;
286   FLATBUFFERS_ASSERT(parser.root_struct_def_);  // call SetRootType()
287   text.reserve(1024);               // Reduce amount of inevitable reallocs.
288   auto root = parser.opts.size_prefixed ?
289       GetSizePrefixedRoot<Table>(flatbuffer) : GetRoot<Table>(flatbuffer);
290   if (!GenStruct(*parser.root_struct_def_, root, 0, parser.opts, _text)) {
291     return false;
292   }
293   text += NewLine(parser.opts);
294   return true;
295 }
296 
TextFileName(const std::string & path,const std::string & file_name)297 std::string TextFileName(const std::string &path,
298                          const std::string &file_name) {
299   return path + file_name + ".json";
300 }
301 
GenerateTextFile(const Parser & parser,const std::string & path,const std::string & file_name)302 bool GenerateTextFile(const Parser &parser, const std::string &path,
303                       const std::string &file_name) {
304   if (!parser.builder_.GetSize() || !parser.root_struct_def_) return true;
305   std::string text;
306   if (!GenerateText(parser, parser.builder_.GetBufferPointer(), &text)) {
307     return false;
308   }
309   return flatbuffers::SaveFile(TextFileName(path, file_name).c_str(), text,
310                                false);
311 }
312 
TextMakeRule(const Parser & parser,const std::string & path,const std::string & file_name)313 std::string TextMakeRule(const Parser &parser, const std::string &path,
314                          const std::string &file_name) {
315   if (!parser.builder_.GetSize() || !parser.root_struct_def_) return "";
316   std::string filebase =
317       flatbuffers::StripPath(flatbuffers::StripExtension(file_name));
318   std::string make_rule = TextFileName(path, filebase) + ": " + file_name;
319   auto included_files =
320       parser.GetIncludedFilesRecursive(parser.root_struct_def_->file);
321   for (auto it = included_files.begin(); it != included_files.end(); ++it) {
322     make_rule += " " + *it;
323   }
324   return make_rule;
325 }
326 
327 }  // namespace flatbuffers
328