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 std::vector<EnumVal const *> enum_values;
55 if (auto ev = type.enum_def->ReverseLookup(static_cast<int64_t>(val))) {
56 enum_values.push_back(ev);
57 } else if (val && type.enum_def->attributes.Lookup("bit_flags")) {
58 for (auto it = type.enum_def->Vals().begin(),
59 e = type.enum_def->Vals().end();
60 it != e; ++it) {
61 if ((*it)->GetAsUInt64() & static_cast<uint64_t>(val))
62 enum_values.push_back(*it);
63 }
64 }
65 if (!enum_values.empty()) {
66 text += '\"';
67 for (auto it = enum_values.begin(), e = enum_values.end(); it != e; ++it)
68 text += (*it)->name + ' ';
69 text[text.length() - 1] = '\"';
70 return true;
71 }
72 }
73
74 if (type.base_type == BASE_TYPE_BOOL) {
75 text += val != 0 ? "true" : "false";
76 } else {
77 text += NumToString(val);
78 }
79
80 return true;
81 }
82
83 // Print a vector or an array of JSON values, comma seperated, wrapped in "[]".
84 template<typename T, typename Container>
PrintContainer(const Container & c,size_t size,Type type,int indent,const IDLOptions & opts,std::string * _text)85 bool PrintContainer(const Container &c, size_t size, Type type, int indent,
86 const IDLOptions &opts, std::string *_text) {
87 std::string &text = *_text;
88 text += "[";
89 text += NewLine(opts);
90 for (uoffset_t i = 0; i < size; i++) {
91 if (i) {
92 if (!opts.protobuf_ascii_alike) text += ",";
93 text += NewLine(opts);
94 }
95 text.append(indent + Indent(opts), ' ');
96 if (IsStruct(type)) {
97 if (!Print(reinterpret_cast<const void *>(c.Data() +
98 i * type.struct_def->bytesize),
99 type, indent + Indent(opts), nullptr, opts, _text)) {
100 return false;
101 }
102 } else {
103 if (!Print(c[i], type, indent + Indent(opts), nullptr, opts, _text)) {
104 return false;
105 }
106 }
107 }
108 text += NewLine(opts);
109 text.append(indent, ' ');
110 text += "]";
111 return true;
112 }
113
114 template<typename T>
PrintVector(const Vector<T> & v,Type type,int indent,const IDLOptions & opts,std::string * _text)115 bool PrintVector(const Vector<T> &v, Type type, int indent,
116 const IDLOptions &opts, std::string *_text) {
117 return PrintContainer<T, Vector<T>>(v, v.size(), type, indent, opts, _text);
118 }
119
120 // Print an array a sequence of JSON values, comma separated, wrapped in "[]".
121 template<typename T>
PrintArray(const Array<T,0xFFFF> & a,size_t size,Type type,int indent,const IDLOptions & opts,std::string * _text)122 bool PrintArray(const Array<T, 0xFFFF> &a, size_t size, Type type, int indent,
123 const IDLOptions &opts, std::string *_text) {
124 return PrintContainer<T, Array<T, 0xFFFF>>(a, size, type, indent, opts,
125 _text);
126 }
127
128 // Specialization of Print above for pointer types.
129 template<>
Print(const void * val,Type type,int indent,Type * union_type,const IDLOptions & opts,std::string * _text)130 bool Print<const void *>(const void *val, Type type, int indent,
131 Type *union_type, const IDLOptions &opts,
132 std::string *_text) {
133 switch (type.base_type) {
134 case BASE_TYPE_UNION:
135 // If this assert hits, you have an corrupt buffer, a union type field
136 // was not present or was out of range.
137 FLATBUFFERS_ASSERT(union_type);
138 return Print<const void *>(val, *union_type, indent, nullptr, opts,
139 _text);
140 case BASE_TYPE_STRUCT:
141 if (!GenStruct(*type.struct_def, reinterpret_cast<const Table *>(val),
142 indent, opts, _text)) {
143 return false;
144 }
145 break;
146 case BASE_TYPE_STRING: {
147 auto s = reinterpret_cast<const String *>(val);
148 if (!EscapeString(s->c_str(), s->size(), _text, opts.allow_non_utf8,
149 opts.natural_utf8)) {
150 return false;
151 }
152 break;
153 }
154 case BASE_TYPE_VECTOR: {
155 const auto vec_type = type.VectorType();
156 // Call PrintVector above specifically for each element type:
157 // clang-format off
158 switch (vec_type.base_type) {
159 #define FLATBUFFERS_TD(ENUM, IDLTYPE, \
160 CTYPE, JTYPE, GTYPE, NTYPE, PTYPE, RTYPE, KTYPE) \
161 case BASE_TYPE_ ## ENUM: \
162 if (!PrintVector<CTYPE>( \
163 *reinterpret_cast<const Vector<CTYPE> *>(val), \
164 vec_type, indent, opts, _text)) { \
165 return false; \
166 } \
167 break;
168 FLATBUFFERS_GEN_TYPES(FLATBUFFERS_TD)
169 #undef FLATBUFFERS_TD
170 }
171 // clang-format on
172 break;
173 }
174 case BASE_TYPE_ARRAY: {
175 const auto vec_type = type.VectorType();
176 // Call PrintArray above specifically for each element type:
177 // clang-format off
178 switch (vec_type.base_type) {
179 #define FLATBUFFERS_TD(ENUM, IDLTYPE, \
180 CTYPE, JTYPE, GTYPE, NTYPE, PTYPE, RTYPE, KTYPE) \
181 case BASE_TYPE_ ## ENUM: \
182 if (!PrintArray<CTYPE>( \
183 *reinterpret_cast<const Array<CTYPE, 0xFFFF> *>(val), \
184 type.fixed_length, \
185 vec_type, indent, opts, _text)) { \
186 return false; \
187 } \
188 break;
189 FLATBUFFERS_GEN_TYPES_SCALAR(FLATBUFFERS_TD)
190 FLATBUFFERS_GEN_TYPES_POINTER(FLATBUFFERS_TD)
191 #undef FLATBUFFERS_TD
192 case BASE_TYPE_ARRAY: FLATBUFFERS_ASSERT(0);
193 }
194 // clang-format on
195 break;
196 }
197 default: FLATBUFFERS_ASSERT(0);
198 }
199 return true;
200 }
201
GetFieldDefault(const FieldDef & fd)202 template<typename T> static T GetFieldDefault(const FieldDef &fd) {
203 T val;
204 auto check = StringToNumber(fd.value.constant.c_str(), &val);
205 (void)check;
206 FLATBUFFERS_ASSERT(check);
207 return val;
208 }
209
210 // Generate text for a scalar field.
211 template<typename T>
GenField(const FieldDef & fd,const Table * table,bool fixed,const IDLOptions & opts,int indent,std::string * _text)212 static bool GenField(const FieldDef &fd, const Table *table, bool fixed,
213 const IDLOptions &opts, int indent, std::string *_text) {
214 return Print(
215 fixed ? reinterpret_cast<const Struct *>(table)->GetField<T>(
216 fd.value.offset)
217 : table->GetField<T>(fd.value.offset, GetFieldDefault<T>(fd)),
218 fd.value.type, indent, nullptr, opts, _text);
219 }
220
221 static bool GenStruct(const StructDef &struct_def, const Table *table,
222 int indent, const IDLOptions &opts, std::string *_text);
223
224 // 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)225 static bool GenFieldOffset(const FieldDef &fd, const Table *table, bool fixed,
226 int indent, Type *union_type, const IDLOptions &opts,
227 std::string *_text) {
228 const void *val = nullptr;
229 if (fixed) {
230 // The only non-scalar fields in structs are structs or arrays.
231 FLATBUFFERS_ASSERT(IsStruct(fd.value.type) || IsArray(fd.value.type));
232 val = reinterpret_cast<const Struct *>(table)->GetStruct<const void *>(
233 fd.value.offset);
234 } else if (fd.flexbuffer) {
235 auto vec = table->GetPointer<const Vector<uint8_t> *>(fd.value.offset);
236 auto root = flexbuffers::GetRoot(vec->data(), vec->size());
237 root.ToString(true, opts.strict_json, *_text);
238 return true;
239 } else if (fd.nested_flatbuffer) {
240 auto vec = table->GetPointer<const Vector<uint8_t> *>(fd.value.offset);
241 auto root = GetRoot<Table>(vec->data());
242 return GenStruct(*fd.nested_flatbuffer, root, indent, opts, _text);
243 } else {
244 val = IsStruct(fd.value.type)
245 ? table->GetStruct<const void *>(fd.value.offset)
246 : table->GetPointer<const void *>(fd.value.offset);
247 }
248 return Print(val, fd.value.type, indent, union_type, opts, _text);
249 }
250
251 // Generate text for a struct or table, values separated by commas, indented,
252 // and bracketed by "{}"
GenStruct(const StructDef & struct_def,const Table * table,int indent,const IDLOptions & opts,std::string * _text)253 static bool GenStruct(const StructDef &struct_def, const Table *table,
254 int indent, const IDLOptions &opts, std::string *_text) {
255 std::string &text = *_text;
256 text += "{";
257 int fieldout = 0;
258 Type *union_type = nullptr;
259 for (auto it = struct_def.fields.vec.begin();
260 it != struct_def.fields.vec.end(); ++it) {
261 FieldDef &fd = **it;
262 auto is_present = struct_def.fixed || table->CheckField(fd.value.offset);
263 auto output_anyway = opts.output_default_scalars_in_json &&
264 IsScalar(fd.value.type.base_type) && !fd.deprecated;
265 if (is_present || output_anyway) {
266 if (fieldout++) {
267 if (!opts.protobuf_ascii_alike) text += ",";
268 }
269 text += NewLine(opts);
270 text.append(indent + Indent(opts), ' ');
271 OutputIdentifier(fd.name, opts, _text);
272 if (!opts.protobuf_ascii_alike ||
273 (fd.value.type.base_type != BASE_TYPE_STRUCT &&
274 fd.value.type.base_type != BASE_TYPE_VECTOR))
275 text += ":";
276 text += " ";
277 switch (fd.value.type.base_type) {
278 // clang-format off
279 #define FLATBUFFERS_TD(ENUM, IDLTYPE, \
280 CTYPE, JTYPE, GTYPE, NTYPE, PTYPE, RTYPE, KTYPE) \
281 case BASE_TYPE_ ## ENUM: \
282 if (!GenField<CTYPE>(fd, table, struct_def.fixed, \
283 opts, indent + Indent(opts), _text)) { \
284 return false; \
285 } \
286 break;
287 FLATBUFFERS_GEN_TYPES_SCALAR(FLATBUFFERS_TD)
288 #undef FLATBUFFERS_TD
289 // Generate drop-thru case statements for all pointer types:
290 #define FLATBUFFERS_TD(ENUM, IDLTYPE, \
291 CTYPE, JTYPE, GTYPE, NTYPE, PTYPE, RTYPE, KTYPE) \
292 case BASE_TYPE_ ## ENUM:
293 FLATBUFFERS_GEN_TYPES_POINTER(FLATBUFFERS_TD)
294 FLATBUFFERS_GEN_TYPE_ARRAY(FLATBUFFERS_TD)
295 #undef FLATBUFFERS_TD
296 if (!GenFieldOffset(fd, table, struct_def.fixed, indent + Indent(opts),
297 union_type, opts, _text)) {
298 return false;
299 }
300 break;
301 // clang-format on
302 }
303 if (fd.value.type.base_type == BASE_TYPE_UTYPE) {
304 auto enum_val = fd.value.type.enum_def->ReverseLookup(
305 table->GetField<uint8_t>(fd.value.offset, 0), true);
306 union_type = enum_val ? &enum_val->union_type : nullptr;
307 }
308 }
309 }
310 text += NewLine(opts);
311 text.append(indent, ' ');
312 text += "}";
313 return true;
314 }
315
316 // 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)317 bool GenerateTextFromTable(const Parser &parser, const void *table,
318 const std::string &table_name, std::string *_text) {
319 auto struct_def = parser.LookupStruct(table_name);
320 if (struct_def == nullptr) {
321 return false;
322 }
323 auto &text = *_text;
324 text.reserve(1024); // Reduce amount of inevitable reallocs.
325 auto root = static_cast<const Table *>(table);
326 if (!GenStruct(*struct_def, root, 0, parser.opts, &text)) {
327 return false;
328 }
329 text += NewLine(parser.opts);
330 return true;
331 }
332
333 // Generate a text representation of a flatbuffer in JSON format.
GenerateText(const Parser & parser,const void * flatbuffer,std::string * _text)334 bool GenerateText(const Parser &parser, const void *flatbuffer,
335 std::string *_text) {
336 std::string &text = *_text;
337 FLATBUFFERS_ASSERT(parser.root_struct_def_); // call SetRootType()
338 text.reserve(1024); // Reduce amount of inevitable reallocs.
339 auto root = parser.opts.size_prefixed ?
340 GetSizePrefixedRoot<Table>(flatbuffer) : GetRoot<Table>(flatbuffer);
341 if (!GenStruct(*parser.root_struct_def_, root, 0, parser.opts, _text)) {
342 return false;
343 }
344 text += NewLine(parser.opts);
345 return true;
346 }
347
TextFileName(const std::string & path,const std::string & file_name)348 std::string TextFileName(const std::string &path,
349 const std::string &file_name) {
350 return path + file_name + ".json";
351 }
352
GenerateTextFile(const Parser & parser,const std::string & path,const std::string & file_name)353 bool GenerateTextFile(const Parser &parser, const std::string &path,
354 const std::string &file_name) {
355 if (!parser.builder_.GetSize() || !parser.root_struct_def_) return true;
356 std::string text;
357 if (!GenerateText(parser, parser.builder_.GetBufferPointer(), &text)) {
358 return false;
359 }
360 return flatbuffers::SaveFile(TextFileName(path, file_name).c_str(), text,
361 false);
362 }
363
TextMakeRule(const Parser & parser,const std::string & path,const std::string & file_name)364 std::string TextMakeRule(const Parser &parser, const std::string &path,
365 const std::string &file_name) {
366 if (!parser.builder_.GetSize() || !parser.root_struct_def_) return "";
367 std::string filebase =
368 flatbuffers::StripPath(flatbuffers::StripExtension(file_name));
369 std::string make_rule = TextFileName(path, filebase) + ": " + file_name;
370 auto included_files =
371 parser.GetIncludedFilesRecursive(parser.root_struct_def_->file);
372 for (auto it = included_files.begin(); it != included_files.end(); ++it) {
373 make_rule += " " + *it;
374 }
375 return make_rule;
376 }
377
378 } // namespace flatbuffers
379