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->Length(), _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
152 // Generate text for a scalar field.
GenField(const FieldDef & fd,const Table * table,bool fixed,const IDLOptions & opts,int indent,std::string * _text)153 template<typename T> static bool GenField(const FieldDef &fd,
154 const Table *table, bool fixed,
155 const IDLOptions &opts,
156 int indent,
157 std::string *_text) {
158 return Print(fixed ?
159 reinterpret_cast<const Struct *>(table)->GetField<T>(fd.value.offset) :
160 table->GetField<T>(fd.value.offset,
161 IsFloat(fd.value.type.base_type) ?
162 static_cast<T>(strtod(fd.value.constant.c_str(), nullptr)) :
163 static_cast<T>(StringToInt(fd.value.constant.c_str()))),
164 fd.value.type, indent, nullptr, opts, _text);
165 }
166
167 static bool GenStruct(const StructDef &struct_def, const Table *table,
168 int indent, const IDLOptions &opts, std::string *_text);
169
170 // 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)171 static bool GenFieldOffset(const FieldDef &fd, const Table *table, bool fixed,
172 int indent, Type *union_type, const IDLOptions &opts,
173 std::string *_text) {
174 const void *val = nullptr;
175 if (fixed) {
176 // The only non-scalar fields in structs are structs.
177 FLATBUFFERS_ASSERT(IsStruct(fd.value.type));
178 val = reinterpret_cast<const Struct *>(table)->GetStruct<const void *>(
179 fd.value.offset);
180 } else if (fd.flexbuffer) {
181 auto vec = table->GetPointer<const Vector<uint8_t> *>(fd.value.offset);
182 auto root = flexbuffers::GetRoot(vec->data(), vec->size());
183 root.ToString(true, opts.strict_json, *_text);
184 return true;
185 } else if (fd.nested_flatbuffer) {
186 auto vec = table->GetPointer<const Vector<uint8_t> *>(fd.value.offset);
187 auto root = GetRoot<Table>(vec->data());
188 return GenStruct(*fd.nested_flatbuffer, root, indent, opts, _text);
189 } else {
190 val = IsStruct(fd.value.type)
191 ? table->GetStruct<const void *>(fd.value.offset)
192 : table->GetPointer<const void *>(fd.value.offset);
193 }
194 return Print(val, fd.value.type, indent, union_type, opts, _text);
195 }
196
197 // Generate text for a struct or table, values separated by commas, indented,
198 // and bracketed by "{}"
GenStruct(const StructDef & struct_def,const Table * table,int indent,const IDLOptions & opts,std::string * _text)199 static bool GenStruct(const StructDef &struct_def, const Table *table,
200 int indent, const IDLOptions &opts, std::string *_text) {
201 std::string &text = *_text;
202 text += "{";
203 int fieldout = 0;
204 Type *union_type = nullptr;
205 for (auto it = struct_def.fields.vec.begin();
206 it != struct_def.fields.vec.end(); ++it) {
207 FieldDef &fd = **it;
208 auto is_present = struct_def.fixed || table->CheckField(fd.value.offset);
209 auto output_anyway = opts.output_default_scalars_in_json &&
210 IsScalar(fd.value.type.base_type) && !fd.deprecated;
211 if (is_present || output_anyway) {
212 if (fieldout++) {
213 if (!opts.protobuf_ascii_alike) text += ",";
214 }
215 text += NewLine(opts);
216 text.append(indent + Indent(opts), ' ');
217 OutputIdentifier(fd.name, opts, _text);
218 if (!opts.protobuf_ascii_alike ||
219 (fd.value.type.base_type != BASE_TYPE_STRUCT &&
220 fd.value.type.base_type != BASE_TYPE_VECTOR))
221 text += ":";
222 text += " ";
223 switch (fd.value.type.base_type) {
224 // clang-format off
225 #define FLATBUFFERS_TD(ENUM, IDLTYPE, \
226 CTYPE, JTYPE, GTYPE, NTYPE, PTYPE, RTYPE) \
227 case BASE_TYPE_ ## ENUM: \
228 if (!GenField<CTYPE>(fd, table, struct_def.fixed, \
229 opts, indent + Indent(opts), _text)) { \
230 return false; \
231 } \
232 break;
233 FLATBUFFERS_GEN_TYPES_SCALAR(FLATBUFFERS_TD)
234 #undef FLATBUFFERS_TD
235 // Generate drop-thru case statements for all pointer types:
236 #define FLATBUFFERS_TD(ENUM, IDLTYPE, \
237 CTYPE, JTYPE, GTYPE, NTYPE, PTYPE, RTYPE) \
238 case BASE_TYPE_ ## ENUM:
239 FLATBUFFERS_GEN_TYPES_POINTER(FLATBUFFERS_TD)
240 #undef FLATBUFFERS_TD
241 if (!GenFieldOffset(fd, table, struct_def.fixed, indent + Indent(opts),
242 union_type, opts, _text)) {
243 return false;
244 }
245 break;
246 // clang-format on
247 }
248 if (fd.value.type.base_type == BASE_TYPE_UTYPE) {
249 auto enum_val = fd.value.type.enum_def->ReverseLookup(
250 table->GetField<uint8_t>(fd.value.offset, 0));
251 union_type = enum_val ? &enum_val->union_type : nullptr;
252 }
253 }
254 }
255 text += NewLine(opts);
256 text.append(indent, ' ');
257 text += "}";
258 return true;
259 }
260
261 // Generate a text representation of a flatbuffer in JSON format.
GenerateText(const Parser & parser,const void * flatbuffer,std::string * _text)262 bool GenerateText(const Parser &parser, const void *flatbuffer,
263 std::string *_text) {
264 std::string &text = *_text;
265 FLATBUFFERS_ASSERT(parser.root_struct_def_); // call SetRootType()
266 text.reserve(1024); // Reduce amount of inevitable reallocs.
267 auto root = parser.opts.size_prefixed ?
268 GetSizePrefixedRoot<Table>(flatbuffer) : GetRoot<Table>(flatbuffer);
269 if (!GenStruct(*parser.root_struct_def_, root, 0, parser.opts, _text)) {
270 return false;
271 }
272 text += NewLine(parser.opts);
273 return true;
274 }
275
TextFileName(const std::string & path,const std::string & file_name)276 std::string TextFileName(const std::string &path,
277 const std::string &file_name) {
278 return path + file_name + ".json";
279 }
280
GenerateTextFile(const Parser & parser,const std::string & path,const std::string & file_name)281 bool GenerateTextFile(const Parser &parser, const std::string &path,
282 const std::string &file_name) {
283 if (!parser.builder_.GetSize() || !parser.root_struct_def_) return true;
284 std::string text;
285 if (!GenerateText(parser, parser.builder_.GetBufferPointer(), &text)) {
286 return false;
287 }
288 return flatbuffers::SaveFile(TextFileName(path, file_name).c_str(), text,
289 false);
290 }
291
TextMakeRule(const Parser & parser,const std::string & path,const std::string & file_name)292 std::string TextMakeRule(const Parser &parser, const std::string &path,
293 const std::string &file_name) {
294 if (!parser.builder_.GetSize() || !parser.root_struct_def_) return "";
295 std::string filebase =
296 flatbuffers::StripPath(flatbuffers::StripExtension(file_name));
297 std::string make_rule = TextFileName(path, filebase) + ": " + file_name;
298 auto included_files =
299 parser.GetIncludedFilesRecursive(parser.root_struct_def_->file);
300 for (auto it = included_files.begin(); it != included_files.end(); ++it) {
301 make_rule += " " + *it;
302 }
303 return make_rule;
304 }
305
306 } // namespace flatbuffers
307