• 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 struct PrintScalarTag {};
27 struct PrintPointerTag {};
28 template<typename T> struct PrintTag { typedef PrintScalarTag type; };
29 template<> struct PrintTag<const void *> { typedef PrintPointerTag type; };
30 
31 struct JsonPrinter {
32   // If indentation is less than 0, that indicates we don't want any newlines
33   // either.
AddNewLineflatbuffers::JsonPrinter34   void AddNewLine() {
35     if (opts.indent_step >= 0) text += '\n';
36   }
37 
AddIndentflatbuffers::JsonPrinter38   void AddIndent(int ident) { text.append(ident, ' '); }
39 
Indentflatbuffers::JsonPrinter40   int Indent() const { return std::max(opts.indent_step, 0); }
41 
42   // Output an identifier with or without quotes depending on strictness.
OutputIdentifierflatbuffers::JsonPrinter43   void OutputIdentifier(const std::string &name) {
44     if (opts.strict_json) text += '\"';
45     text += name;
46     if (opts.strict_json) text += '\"';
47   }
48 
49   // Print (and its template specialization below for pointers) generate text
50   // for a single FlatBuffer value into JSON format.
51   // The general case for scalars:
52   template<typename T>
PrintScalarflatbuffers::JsonPrinter53   bool PrintScalar(T val, const Type &type, int /*indent*/) {
54     if (IsBool(type.base_type)) {
55       text += val != 0 ? "true" : "false";
56       return true;  // done
57     }
58 
59     if (opts.output_enum_identifiers && type.enum_def) {
60       const auto &enum_def = *type.enum_def;
61       if (auto ev = enum_def.ReverseLookup(static_cast<int64_t>(val))) {
62         text += '\"';
63         text += ev->name;
64         text += '\"';
65         return true;  // done
66       } else if (val && enum_def.attributes.Lookup("bit_flags")) {
67         const auto entry_len = text.length();
68         const auto u64 = static_cast<uint64_t>(val);
69         uint64_t mask = 0;
70         text += '\"';
71         for (auto it = enum_def.Vals().begin(), e = enum_def.Vals().end();
72              it != e; ++it) {
73           auto f = (*it)->GetAsUInt64();
74           if (f & u64) {
75             mask |= f;
76             text += (*it)->name;
77             text += ' ';
78           }
79         }
80         // Don't slice if (u64 != mask)
81         if (mask && (u64 == mask)) {
82           text[text.length() - 1] = '\"';
83           return true;  // done
84         }
85         text.resize(entry_len);  // restore
86       }
87       // print as numeric value
88     }
89 
90     text += NumToString(val);
91     return true;
92   }
93 
AddCommaflatbuffers::JsonPrinter94   void AddComma() {
95     if (!opts.protobuf_ascii_alike) text += ',';
96   }
97 
98   // Print a vector or an array of JSON values, comma seperated, wrapped in
99   // "[]".
100   template<typename Container>
PrintContainerflatbuffers::JsonPrinter101   bool PrintContainer(PrintScalarTag, const Container &c, size_t size,
102                       const Type &type, int indent, const uint8_t *) {
103     const auto elem_indent = indent + Indent();
104     text += '[';
105     AddNewLine();
106     for (uoffset_t i = 0; i < size; i++) {
107       if (i) {
108         AddComma();
109         AddNewLine();
110       }
111       AddIndent(elem_indent);
112       if (!PrintScalar(c[i], type, elem_indent)) { return false; }
113     }
114     AddNewLine();
115     AddIndent(indent);
116     text += ']';
117     return true;
118   }
119 
120   // Print a vector or an array of JSON values, comma seperated, wrapped in
121   // "[]".
122   template<typename Container>
PrintContainerflatbuffers::JsonPrinter123   bool PrintContainer(PrintPointerTag, const Container &c, size_t size,
124                       const Type &type, int indent, const uint8_t *prev_val) {
125     const auto is_struct = IsStruct(type);
126     const auto elem_indent = indent + Indent();
127     text += '[';
128     AddNewLine();
129     for (uoffset_t i = 0; i < size; i++) {
130       if (i) {
131         AddComma();
132         AddNewLine();
133       }
134       AddIndent(elem_indent);
135       auto ptr = is_struct ? reinterpret_cast<const void *>(
136                                  c.Data() + type.struct_def->bytesize * i)
137                            : c[i];
138       if (!PrintOffset(ptr, type, elem_indent, prev_val,
139                        static_cast<soffset_t>(i))) {
140         return false;
141       }
142     }
143     AddNewLine();
144     AddIndent(indent);
145     text += ']';
146     return true;
147   }
148 
149   template<typename T>
PrintVectorflatbuffers::JsonPrinter150   bool PrintVector(const void *val, const Type &type, int indent,
151                    const uint8_t *prev_val) {
152     typedef Vector<T> Container;
153     typedef typename PrintTag<typename Container::return_type>::type tag;
154     auto &vec = *reinterpret_cast<const Container *>(val);
155     return PrintContainer<Container>(tag(), vec, vec.size(), type, indent,
156                                      prev_val);
157   }
158 
159   // Print an array a sequence of JSON values, comma separated, wrapped in "[]".
160   template<typename T>
PrintArrayflatbuffers::JsonPrinter161   bool PrintArray(const void *val, size_t size, const Type &type, int indent) {
162     typedef Array<T, 0xFFFF> Container;
163     typedef typename PrintTag<typename Container::return_type>::type tag;
164     auto &arr = *reinterpret_cast<const Container *>(val);
165     return PrintContainer<Container>(tag(), arr, size, type, indent, nullptr);
166   }
167 
PrintOffsetflatbuffers::JsonPrinter168   bool PrintOffset(const void *val, const Type &type, int indent,
169                    const uint8_t *prev_val, soffset_t vector_index) {
170     switch (type.base_type) {
171       case BASE_TYPE_UNION: {
172         // If this assert hits, you have an corrupt buffer, a union type field
173         // was not present or was out of range.
174         FLATBUFFERS_ASSERT(prev_val);
175         auto union_type_byte = *prev_val;  // Always a uint8_t.
176         if (vector_index >= 0) {
177           auto type_vec = reinterpret_cast<const Vector<uint8_t> *>(
178               prev_val + ReadScalar<uoffset_t>(prev_val));
179           union_type_byte = type_vec->Get(static_cast<uoffset_t>(vector_index));
180         }
181         auto enum_val = type.enum_def->ReverseLookup(union_type_byte, true);
182         if (enum_val) {
183           return PrintOffset(val, enum_val->union_type, indent, nullptr, -1);
184         } else {
185           return false;
186         }
187       }
188       case BASE_TYPE_STRUCT:
189         return GenStruct(*type.struct_def, reinterpret_cast<const Table *>(val),
190                          indent);
191       case BASE_TYPE_STRING: {
192         auto s = reinterpret_cast<const String *>(val);
193         return EscapeString(s->c_str(), s->size(), &text, opts.allow_non_utf8,
194                             opts.natural_utf8);
195       }
196       case BASE_TYPE_VECTOR: {
197         const auto vec_type = type.VectorType();
198         // Call PrintVector above specifically for each element type:
199         // clang-format off
200         switch (vec_type.base_type) {
201         #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, ...) \
202           case BASE_TYPE_ ## ENUM: \
203             if (!PrintVector<CTYPE>( \
204                   val, vec_type, indent, prev_val)) { \
205               return false; \
206             } \
207             break;
208           FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
209         #undef FLATBUFFERS_TD
210         }
211         // clang-format on
212         return true;
213       }
214       case BASE_TYPE_ARRAY: {
215         const auto vec_type = type.VectorType();
216         // Call PrintArray above specifically for each element type:
217         // clang-format off
218         switch (vec_type.base_type) {
219         #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, ...) \
220           case BASE_TYPE_ ## ENUM: \
221             if (!PrintArray<CTYPE>( \
222                 val, type.fixed_length, vec_type, indent)) { \
223             return false; \
224             } \
225             break;
226             FLATBUFFERS_GEN_TYPES_SCALAR(FLATBUFFERS_TD)
227               // Arrays of scalars or structs are only possible.
228               FLATBUFFERS_GEN_TYPES_POINTER(FLATBUFFERS_TD)
229         #undef FLATBUFFERS_TD
230           case BASE_TYPE_ARRAY: FLATBUFFERS_ASSERT(0);
231         }
232         // clang-format on
233         return true;
234       }
235       default: FLATBUFFERS_ASSERT(0); return false;
236     }
237   }
238 
GetFieldDefaultflatbuffers::JsonPrinter239   template<typename T> static T GetFieldDefault(const FieldDef &fd) {
240     T val;
241     auto check = StringToNumber(fd.value.constant.c_str(), &val);
242     (void)check;
243     FLATBUFFERS_ASSERT(check);
244     return val;
245   }
246 
247   // Generate text for a scalar field.
248   template<typename T>
GenFieldflatbuffers::JsonPrinter249   bool GenField(const FieldDef &fd, const Table *table, bool fixed,
250                 int indent) {
251     return PrintScalar(
252         fixed ? reinterpret_cast<const Struct *>(table)->GetField<T>(
253                     fd.value.offset)
254               : table->GetField<T>(fd.value.offset, GetFieldDefault<T>(fd)),
255         fd.value.type, indent);
256   }
257 
258   // Generate text for non-scalar field.
GenFieldOffsetflatbuffers::JsonPrinter259   bool GenFieldOffset(const FieldDef &fd, const Table *table, bool fixed,
260                       int indent, const uint8_t *prev_val) {
261     const void *val = nullptr;
262     if (fixed) {
263       // The only non-scalar fields in structs are structs or arrays.
264       FLATBUFFERS_ASSERT(IsStruct(fd.value.type) || IsArray(fd.value.type));
265       val = reinterpret_cast<const Struct *>(table)->GetStruct<const void *>(
266           fd.value.offset);
267     } else if (fd.flexbuffer) {
268       auto vec = table->GetPointer<const Vector<uint8_t> *>(fd.value.offset);
269       auto root = flexbuffers::GetRoot(vec->data(), vec->size());
270       root.ToString(true, opts.strict_json, text);
271       return true;
272     } else if (fd.nested_flatbuffer) {
273       auto vec = table->GetPointer<const Vector<uint8_t> *>(fd.value.offset);
274       auto root = GetRoot<Table>(vec->data());
275       return GenStruct(*fd.nested_flatbuffer, root, indent);
276     } else {
277       val = IsStruct(fd.value.type)
278                 ? table->GetStruct<const void *>(fd.value.offset)
279                 : table->GetPointer<const void *>(fd.value.offset);
280     }
281     return PrintOffset(val, fd.value.type, indent, prev_val, -1);
282   }
283 
284   // Generate text for a struct or table, values separated by commas, indented,
285   // and bracketed by "{}"
GenStructflatbuffers::JsonPrinter286   bool GenStruct(const StructDef &struct_def, const Table *table, int indent) {
287     text += '{';
288     int fieldout = 0;
289     const uint8_t *prev_val = nullptr;
290     const auto elem_indent = indent + Indent();
291     for (auto it = struct_def.fields.vec.begin();
292          it != struct_def.fields.vec.end(); ++it) {
293       FieldDef &fd = **it;
294       auto is_present = struct_def.fixed || table->CheckField(fd.value.offset);
295       auto output_anyway = opts.output_default_scalars_in_json &&
296                            IsScalar(fd.value.type.base_type) && !fd.deprecated;
297       if (is_present || output_anyway) {
298         if (fieldout++) { AddComma(); }
299         AddNewLine();
300         AddIndent(elem_indent);
301         OutputIdentifier(fd.name);
302         if (!opts.protobuf_ascii_alike ||
303             (fd.value.type.base_type != BASE_TYPE_STRUCT &&
304              fd.value.type.base_type != BASE_TYPE_VECTOR))
305           text += ':';
306         text += ' ';
307         // clang-format off
308         switch (fd.value.type.base_type) {
309         #define FLATBUFFERS_TD(ENUM, IDLTYPE, CTYPE, ...) \
310           case BASE_TYPE_ ## ENUM: \
311             if (!GenField<CTYPE>(fd, table, struct_def.fixed, elem_indent)) { \
312               return false; \
313             } \
314             break;
315             FLATBUFFERS_GEN_TYPES_SCALAR(FLATBUFFERS_TD)
316         #undef FLATBUFFERS_TD
317         // Generate drop-thru case statements for all pointer types:
318         #define FLATBUFFERS_TD(ENUM, ...) \
319           case BASE_TYPE_ ## ENUM:
320               FLATBUFFERS_GEN_TYPES_POINTER(FLATBUFFERS_TD)
321               FLATBUFFERS_GEN_TYPE_ARRAY(FLATBUFFERS_TD)
322         #undef FLATBUFFERS_TD
323               if (!GenFieldOffset(fd, table, struct_def.fixed, elem_indent, prev_val)) {
324                 return false;
325               }
326             break;
327         }
328         // clang-format on
329         // Track prev val for use with union types.
330         if (struct_def.fixed) {
331           prev_val = reinterpret_cast<const uint8_t *>(table) + fd.value.offset;
332         } else {
333           prev_val = table->GetAddressOf(fd.value.offset);
334         }
335       }
336     }
337     AddNewLine();
338     AddIndent(indent);
339     text += '}';
340     return true;
341   }
342 
JsonPrinterflatbuffers::JsonPrinter343   JsonPrinter(const Parser &parser, std::string &dest)
344       : opts(parser.opts), text(dest) {
345     text.reserve(1024);  // Reduce amount of inevitable reallocs.
346   }
347 
348   const IDLOptions &opts;
349   std::string &text;
350 };
351 
GenerateTextImpl(const Parser & parser,const Table * table,const StructDef & struct_def,std::string * _text)352 static bool GenerateTextImpl(const Parser &parser, const Table *table,
353                              const StructDef &struct_def, std::string *_text) {
354   JsonPrinter printer(parser, *_text);
355   if (!printer.GenStruct(struct_def, table, 0)) { return false; }
356   printer.AddNewLine();
357   return true;
358 }
359 
360 // 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)361 bool GenerateTextFromTable(const Parser &parser, const void *table,
362                            const std::string &table_name, std::string *_text) {
363   auto struct_def = parser.LookupStruct(table_name);
364   if (struct_def == nullptr) { return false; }
365   auto root = static_cast<const Table *>(table);
366   return GenerateTextImpl(parser, root, *struct_def, _text);
367 }
368 
369 // Generate a text representation of a flatbuffer in JSON format.
GenerateText(const Parser & parser,const void * flatbuffer,std::string * _text)370 bool GenerateText(const Parser &parser, const void *flatbuffer,
371                   std::string *_text) {
372   FLATBUFFERS_ASSERT(parser.root_struct_def_);  // call SetRootType()
373   auto root = parser.opts.size_prefixed ? GetSizePrefixedRoot<Table>(flatbuffer)
374                                         : GetRoot<Table>(flatbuffer);
375   return GenerateTextImpl(parser, root, *parser.root_struct_def_, _text);
376 }
377 
TextFileName(const std::string & path,const std::string & file_name)378 static std::string TextFileName(const std::string &path,
379                                 const std::string &file_name) {
380   return path + file_name + ".json";
381 }
382 
GenerateTextFile(const Parser & parser,const std::string & path,const std::string & file_name)383 bool GenerateTextFile(const Parser &parser, const std::string &path,
384                       const std::string &file_name) {
385   if (parser.opts.use_flexbuffers) {
386     std::string json;
387     parser.flex_root_.ToString(true, parser.opts.strict_json, json);
388     return flatbuffers::SaveFile(TextFileName(path, file_name).c_str(),
389                                  json.c_str(), json.size(), true);
390   }
391   if (!parser.builder_.GetSize() || !parser.root_struct_def_) return true;
392   std::string text;
393   if (!GenerateText(parser, parser.builder_.GetBufferPointer(), &text)) {
394     return false;
395   }
396   return flatbuffers::SaveFile(TextFileName(path, file_name).c_str(), text,
397                                false);
398 }
399 
TextMakeRule(const Parser & parser,const std::string & path,const std::string & file_name)400 std::string TextMakeRule(const Parser &parser, const std::string &path,
401                          const std::string &file_name) {
402   if (!parser.builder_.GetSize() || !parser.root_struct_def_) return "";
403   std::string filebase =
404       flatbuffers::StripPath(flatbuffers::StripExtension(file_name));
405   std::string make_rule = TextFileName(path, filebase) + ": " + file_name;
406   auto included_files =
407       parser.GetIncludedFilesRecursive(parser.root_struct_def_->file);
408   for (auto it = included_files.begin(); it != included_files.end(); ++it) {
409     make_rule += " " + *it;
410   }
411   return make_rule;
412 }
413 
414 }  // namespace flatbuffers
415