blob: 5cb6a9dcb221338d7ba743def46b312b100b1d4a [file] [log] [blame]
Austin Schuhe89fa2d2019-08-14 20:24:23 -07001/*
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#include <iostream>
Austin Schuh272c6132020-11-14 16:37:52 -080018
Austin Schuhe89fa2d2019-08-14 20:24:23 -070019#include "flatbuffers/code_generators.h"
20#include "flatbuffers/idl.h"
21#include "flatbuffers/util.h"
22
23namespace flatbuffers {
24
Austin Schuhe89fa2d2019-08-14 20:24:23 -070025namespace jsons {
26
Austin Schuh2dd86a92022-09-14 21:19:23 -070027namespace {
28
29template<class T>
30static std::string GenFullName(const T *enum_def) {
Austin Schuhe89fa2d2019-08-14 20:24:23 -070031 std::string full_name;
32 const auto &name_spaces = enum_def->defined_namespace->components;
33 for (auto ns = name_spaces.cbegin(); ns != name_spaces.cend(); ++ns) {
34 full_name.append(*ns + "_");
35 }
36 full_name.append(enum_def->name);
37 return full_name;
38}
39
Austin Schuh2dd86a92022-09-14 21:19:23 -070040template<class T>
41static std::string GenTypeRef(const T *enum_def) {
Austin Schuhe89fa2d2019-08-14 20:24:23 -070042 return "\"$ref\" : \"#/definitions/" + GenFullName(enum_def) + "\"";
43}
44
Austin Schuh2dd86a92022-09-14 21:19:23 -070045static std::string GenType(const std::string &name) {
Austin Schuhe89fa2d2019-08-14 20:24:23 -070046 return "\"type\" : \"" + name + "\"";
47}
48
Austin Schuh2dd86a92022-09-14 21:19:23 -070049static std::string GenType(BaseType type) {
Austin Schuh272c6132020-11-14 16:37:52 -080050 switch (type) {
51 case BASE_TYPE_BOOL: return "\"type\" : \"boolean\"";
52 case BASE_TYPE_CHAR:
53 return "\"type\" : \"integer\", \"minimum\" : " +
54 NumToString(std::numeric_limits<int8_t>::min()) +
55 ", \"maximum\" : " +
James Kuszmaul8e62b022022-03-22 09:33:25 -070056 NumToString(std::numeric_limits<int8_t>::max());
Austin Schuh272c6132020-11-14 16:37:52 -080057 case BASE_TYPE_UCHAR:
58 return "\"type\" : \"integer\", \"minimum\" : 0, \"maximum\" :" +
James Kuszmaul8e62b022022-03-22 09:33:25 -070059 NumToString(std::numeric_limits<uint8_t>::max());
Austin Schuh272c6132020-11-14 16:37:52 -080060 case BASE_TYPE_SHORT:
61 return "\"type\" : \"integer\", \"minimum\" : " +
62 NumToString(std::numeric_limits<int16_t>::min()) +
63 ", \"maximum\" : " +
64 NumToString(std::numeric_limits<int16_t>::max());
65 case BASE_TYPE_USHORT:
66 return "\"type\" : \"integer\", \"minimum\" : 0, \"maximum\" : " +
67 NumToString(std::numeric_limits<uint16_t>::max());
68 case BASE_TYPE_INT:
69 return "\"type\" : \"integer\", \"minimum\" : " +
70 NumToString(std::numeric_limits<int32_t>::min()) +
71 ", \"maximum\" : " +
72 NumToString(std::numeric_limits<int32_t>::max());
73 case BASE_TYPE_UINT:
74 return "\"type\" : \"integer\", \"minimum\" : 0, \"maximum\" : " +
75 NumToString(std::numeric_limits<uint32_t>::max());
76 case BASE_TYPE_LONG:
77 return "\"type\" : \"integer\", \"minimum\" : " +
78 NumToString(std::numeric_limits<int64_t>::min()) +
79 ", \"maximum\" : " +
80 NumToString(std::numeric_limits<int64_t>::max());
81 case BASE_TYPE_ULONG:
82 return "\"type\" : \"integer\", \"minimum\" : 0, \"maximum\" : " +
83 NumToString(std::numeric_limits<uint64_t>::max());
84 case BASE_TYPE_FLOAT:
85 case BASE_TYPE_DOUBLE: return "\"type\" : \"number\"";
86 case BASE_TYPE_STRING: return "\"type\" : \"string\"";
87 default: return "";
Austin Schuhe89fa2d2019-08-14 20:24:23 -070088 }
Austin Schuh272c6132020-11-14 16:37:52 -080089}
90
Austin Schuh2dd86a92022-09-14 21:19:23 -070091static std::string GenBaseType(const Type &type) {
Austin Schuh272c6132020-11-14 16:37:52 -080092 if (type.struct_def != nullptr) { return GenTypeRef(type.struct_def); }
93 if (type.enum_def != nullptr) { return GenTypeRef(type.enum_def); }
Austin Schuh58b9b472020-11-25 19:12:44 -080094 return GenType(type.base_type);
95}
96
Austin Schuh2dd86a92022-09-14 21:19:23 -070097static std::string GenArrayType(const Type &type) {
Austin Schuh58b9b472020-11-25 19:12:44 -080098 std::string element_type;
99 if (type.struct_def != nullptr) {
100 element_type = GenTypeRef(type.struct_def);
101 } else if (type.enum_def != nullptr) {
102 element_type = GenTypeRef(type.enum_def);
103 } else {
104 element_type = GenType(type.element);
Austin Schuh272c6132020-11-14 16:37:52 -0800105 }
Austin Schuh58b9b472020-11-25 19:12:44 -0800106
107 return "\"type\" : \"array\", \"items\" : {" + element_type + "}";
Austin Schuh272c6132020-11-14 16:37:52 -0800108}
109
Austin Schuh2dd86a92022-09-14 21:19:23 -0700110static std::string GenType(const Type &type) {
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700111 switch (type.base_type) {
112 case BASE_TYPE_ARRAY: FLATBUFFERS_FALLTHROUGH(); // fall thru
113 case BASE_TYPE_VECTOR: {
Austin Schuh58b9b472020-11-25 19:12:44 -0800114 return GenArrayType(type);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700115 }
116 case BASE_TYPE_STRUCT: {
117 return GenTypeRef(type.struct_def);
118 }
119 case BASE_TYPE_UNION: {
120 std::string union_type_string("\"anyOf\": [");
121 const auto &union_types = type.enum_def->Vals();
122 for (auto ut = union_types.cbegin(); ut < union_types.cend(); ++ut) {
Austin Schuh272c6132020-11-14 16:37:52 -0800123 const auto &union_type = *ut;
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700124 if (union_type->union_type.base_type == BASE_TYPE_NONE) { continue; }
125 if (union_type->union_type.base_type == BASE_TYPE_STRUCT) {
126 union_type_string.append(
127 "{ " + GenTypeRef(union_type->union_type.struct_def) + " }");
128 }
129 if (union_type != *type.enum_def->Vals().rbegin()) {
130 union_type_string.append(",");
131 }
132 }
133 union_type_string.append("]");
134 return union_type_string;
135 }
136 case BASE_TYPE_UTYPE: return GenTypeRef(type.enum_def);
Austin Schuh272c6132020-11-14 16:37:52 -0800137 default: {
138 return GenBaseType(type);
139 }
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700140 }
141}
142
Austin Schuh2dd86a92022-09-14 21:19:23 -0700143} // namespace
144
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700145class JsonSchemaGenerator : public BaseGenerator {
146 private:
Austin Schuh272c6132020-11-14 16:37:52 -0800147 std::string code_;
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700148
149 public:
150 JsonSchemaGenerator(const Parser &parser, const std::string &path,
151 const std::string &file_name)
Austin Schuh272c6132020-11-14 16:37:52 -0800152 : BaseGenerator(parser, path, file_name, "", "", "json") {}
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700153
154 explicit JsonSchemaGenerator(const BaseGenerator &base_generator)
155 : BaseGenerator(base_generator) {}
156
Austin Schuh272c6132020-11-14 16:37:52 -0800157 std::string GeneratedFileName(const std::string &path,
158 const std::string &file_name,
159 const IDLOptions &options /* unused */) const {
160 (void)options;
161 return path + file_name + ".schema.json";
162 }
163
164 // If indentation is less than 0, that indicates we don't want any newlines
165 // either.
Austin Schuh58b9b472020-11-25 19:12:44 -0800166 std::string NewLine() const {
Austin Schuh272c6132020-11-14 16:37:52 -0800167 return parser_.opts.indent_step >= 0 ? "\n" : "";
168 }
169
Austin Schuh58b9b472020-11-25 19:12:44 -0800170 std::string Indent(int indent) const {
171 const auto num_spaces = indent * std::max(parser_.opts.indent_step, 0);
172 return std::string(num_spaces, ' ');
Austin Schuh272c6132020-11-14 16:37:52 -0800173 }
174
James Kuszmaul8e62b022022-03-22 09:33:25 -0700175 std::string PrepareDescription(
176 const std::vector<std::string> &comment_lines) {
177 std::string comment;
178 for (auto line_iterator = comment_lines.cbegin();
179 line_iterator != comment_lines.cend(); ++line_iterator) {
180 const auto &comment_line = *line_iterator;
181
182 // remove leading and trailing spaces from comment line
183 const auto start = std::find_if(comment_line.begin(), comment_line.end(),
184 [](char c) { return !isspace(c); });
185 const auto end =
186 std::find_if(comment_line.rbegin(), comment_line.rend(), [](char c) {
187 return !isspace(c);
188 }).base();
189 if (start < end) {
190 comment.append(start, end);
191 } else {
192 comment.append(comment_line);
193 }
194
195 if (line_iterator + 1 != comment_lines.cend()) comment.append("\n");
196 }
197 if (!comment.empty()) {
198 std::string description;
199 if (EscapeString(comment.c_str(), comment.length(), &description, true,
200 true)) {
201 return description;
202 }
203 return "";
204 }
205 return "";
206 }
207
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700208 bool generate() {
Austin Schuh272c6132020-11-14 16:37:52 -0800209 code_ = "";
James Kuszmaul8e62b022022-03-22 09:33:25 -0700210 if (parser_.root_struct_def_ == nullptr) {
211 std::cerr << "Error: Binary schema not generated, no root struct found\n";
212 return false;
213 }
Austin Schuh272c6132020-11-14 16:37:52 -0800214 code_ += "{" + NewLine();
215 code_ += Indent(1) +
216 "\"$schema\": \"https://json-schema.org/draft/2019-09/schema\"," +
217 NewLine();
218 code_ += Indent(1) + "\"definitions\": {" + NewLine();
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700219 for (auto e = parser_.enums_.vec.cbegin(); e != parser_.enums_.vec.cend();
220 ++e) {
Austin Schuh272c6132020-11-14 16:37:52 -0800221 code_ += Indent(2) + "\"" + GenFullName(*e) + "\" : {" + NewLine();
222 code_ += Indent(3) + GenType("string") + "," + NewLine();
Austin Schuh58b9b472020-11-25 19:12:44 -0800223 auto enumdef(Indent(3) + "\"enum\": [");
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700224 for (auto enum_value = (*e)->Vals().begin();
225 enum_value != (*e)->Vals().end(); ++enum_value) {
226 enumdef.append("\"" + (*enum_value)->name + "\"");
227 if (*enum_value != (*e)->Vals().back()) { enumdef.append(", "); }
228 }
229 enumdef.append("]");
Austin Schuh272c6132020-11-14 16:37:52 -0800230 code_ += enumdef + NewLine();
231 code_ += Indent(2) + "}," + NewLine(); // close type
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700232 }
233 for (auto s = parser_.structs_.vec.cbegin();
234 s != parser_.structs_.vec.cend(); ++s) {
235 const auto &structure = *s;
Austin Schuh272c6132020-11-14 16:37:52 -0800236 code_ += Indent(2) + "\"" + GenFullName(structure) + "\" : {" + NewLine();
237 code_ += Indent(3) + GenType("object") + "," + NewLine();
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700238 const auto &comment_lines = structure->doc_comment;
James Kuszmaul8e62b022022-03-22 09:33:25 -0700239 auto comment = PrepareDescription(comment_lines);
240 if (comment != "") {
241 code_ += Indent(3) + "\"description\" : " + comment + "," + NewLine();
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700242 }
James Kuszmaul8e62b022022-03-22 09:33:25 -0700243
Austin Schuh272c6132020-11-14 16:37:52 -0800244 code_ += Indent(3) + "\"properties\" : {" + NewLine();
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700245
246 const auto &properties = structure->fields.vec;
247 for (auto prop = properties.cbegin(); prop != properties.cend(); ++prop) {
248 const auto &property = *prop;
249 std::string arrayInfo = "";
250 if (IsArray(property->value.type)) {
Austin Schuh272c6132020-11-14 16:37:52 -0800251 arrayInfo = "," + NewLine() + Indent(8) + "\"minItems\": " +
Austin Schuh58b9b472020-11-25 19:12:44 -0800252 NumToString(property->value.type.fixed_length) + "," +
253 NewLine() + Indent(8) + "\"maxItems\": " +
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700254 NumToString(property->value.type.fixed_length);
255 }
Austin Schuh272c6132020-11-14 16:37:52 -0800256 std::string deprecated_info = "";
257 if (property->deprecated) {
Austin Schuh58b9b472020-11-25 19:12:44 -0800258 deprecated_info =
James Kuszmaul8e62b022022-03-22 09:33:25 -0700259 "," + NewLine() + Indent(8) + "\"deprecated\" : true";
Austin Schuh272c6132020-11-14 16:37:52 -0800260 }
261 std::string typeLine = Indent(4) + "\"" + property->name + "\"";
262 typeLine += " : {" + NewLine() + Indent(8);
263 typeLine += GenType(property->value.type);
264 typeLine += arrayInfo;
265 typeLine += deprecated_info;
James Kuszmaul8e62b022022-03-22 09:33:25 -0700266 auto description = PrepareDescription(property->doc_comment);
267 if (description != "") {
268 typeLine +=
269 "," + NewLine() + Indent(8) + "\"description\" : " + description;
270 }
271
Austin Schuh272c6132020-11-14 16:37:52 -0800272 typeLine += NewLine() + Indent(7) + "}";
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700273 if (property != properties.back()) { typeLine.append(","); }
Austin Schuh272c6132020-11-14 16:37:52 -0800274 code_ += typeLine + NewLine();
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700275 }
Austin Schuh272c6132020-11-14 16:37:52 -0800276 code_ += Indent(3) + "}," + NewLine(); // close properties
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700277
278 std::vector<FieldDef *> requiredProperties;
279 std::copy_if(properties.begin(), properties.end(),
280 back_inserter(requiredProperties),
James Kuszmaul8e62b022022-03-22 09:33:25 -0700281 [](FieldDef const *prop) { return prop->IsRequired(); });
Austin Schuh58b9b472020-11-25 19:12:44 -0800282 if (!requiredProperties.empty()) {
283 auto required_string(Indent(3) + "\"required\" : [");
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700284 for (auto req_prop = requiredProperties.cbegin();
285 req_prop != requiredProperties.cend(); ++req_prop) {
286 required_string.append("\"" + (*req_prop)->name + "\"");
287 if (*req_prop != requiredProperties.back()) {
288 required_string.append(", ");
289 }
290 }
291 required_string.append("],");
Austin Schuh272c6132020-11-14 16:37:52 -0800292 code_ += required_string + NewLine();
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700293 }
Austin Schuh272c6132020-11-14 16:37:52 -0800294 code_ += Indent(3) + "\"additionalProperties\" : false" + NewLine();
Austin Schuh58b9b472020-11-25 19:12:44 -0800295 auto closeType(Indent(2) + "}");
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700296 if (*s != parser_.structs_.vec.back()) { closeType.append(","); }
Austin Schuh272c6132020-11-14 16:37:52 -0800297 code_ += closeType + NewLine(); // close type
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700298 }
Austin Schuh272c6132020-11-14 16:37:52 -0800299 code_ += Indent(1) + "}," + NewLine(); // close definitions
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700300
301 // mark root type
Austin Schuh272c6132020-11-14 16:37:52 -0800302 code_ += Indent(1) + "\"$ref\" : \"#/definitions/" +
303 GenFullName(parser_.root_struct_def_) + "\"" + NewLine();
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700304
Austin Schuh272c6132020-11-14 16:37:52 -0800305 code_ += "}" + NewLine(); // close schema root
306 return true;
307 }
308
Austin Schuh58b9b472020-11-25 19:12:44 -0800309 bool save() const {
James Kuszmaul8e62b022022-03-22 09:33:25 -0700310 const auto file_path = GeneratedFileName(path_, file_name_, parser_.opts);
Austin Schuh272c6132020-11-14 16:37:52 -0800311 return SaveFile(file_path.c_str(), code_, false);
312 }
313
Austin Schuh58b9b472020-11-25 19:12:44 -0800314 const std::string getJson() { return code_; }
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700315};
316} // namespace jsons
317
318bool GenerateJsonSchema(const Parser &parser, const std::string &path,
319 const std::string &file_name) {
320 jsons::JsonSchemaGenerator generator(parser, path, file_name);
Austin Schuh272c6132020-11-14 16:37:52 -0800321 if (!generator.generate()) { return false; }
322 return generator.save();
323}
324
325bool GenerateJsonSchema(const Parser &parser, std::string *json) {
326 jsons::JsonSchemaGenerator generator(parser, "", "");
327 if (!generator.generate()) { return false; }
328 *json = generator.getJson();
329 return true;
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700330}
331} // namespace flatbuffers