blob: 796d1e20ca60d591b93cf8e8ad15975a0fc951a4 [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
James Kuszmaul3b15b0c2022-11-08 14:03:16 -080017#include <algorithm>
Austin Schuhe89fa2d2019-08-14 20:24:23 -070018#include <iostream>
James Kuszmaul3b15b0c2022-11-08 14:03:16 -080019#include <limits>
Austin Schuh272c6132020-11-14 16:37:52 -080020
Austin Schuhe89fa2d2019-08-14 20:24:23 -070021#include "flatbuffers/code_generators.h"
22#include "flatbuffers/idl.h"
23#include "flatbuffers/util.h"
24
25namespace flatbuffers {
26
Austin Schuhe89fa2d2019-08-14 20:24:23 -070027namespace jsons {
28
Austin Schuh2dd86a92022-09-14 21:19:23 -070029namespace {
30
31template<class T>
32static std::string GenFullName(const T *enum_def) {
Austin Schuhe89fa2d2019-08-14 20:24:23 -070033 std::string full_name;
34 const auto &name_spaces = enum_def->defined_namespace->components;
35 for (auto ns = name_spaces.cbegin(); ns != name_spaces.cend(); ++ns) {
36 full_name.append(*ns + "_");
37 }
38 full_name.append(enum_def->name);
39 return full_name;
40}
41
Austin Schuh2dd86a92022-09-14 21:19:23 -070042template<class T>
43static std::string GenTypeRef(const T *enum_def) {
Austin Schuhe89fa2d2019-08-14 20:24:23 -070044 return "\"$ref\" : \"#/definitions/" + GenFullName(enum_def) + "\"";
45}
46
Austin Schuh2dd86a92022-09-14 21:19:23 -070047static std::string GenType(const std::string &name) {
Austin Schuhe89fa2d2019-08-14 20:24:23 -070048 return "\"type\" : \"" + name + "\"";
49}
50
Austin Schuh2dd86a92022-09-14 21:19:23 -070051static std::string GenType(BaseType type) {
Austin Schuh272c6132020-11-14 16:37:52 -080052 switch (type) {
53 case BASE_TYPE_BOOL: return "\"type\" : \"boolean\"";
54 case BASE_TYPE_CHAR:
55 return "\"type\" : \"integer\", \"minimum\" : " +
56 NumToString(std::numeric_limits<int8_t>::min()) +
57 ", \"maximum\" : " +
James Kuszmaul8e62b022022-03-22 09:33:25 -070058 NumToString(std::numeric_limits<int8_t>::max());
Austin Schuh272c6132020-11-14 16:37:52 -080059 case BASE_TYPE_UCHAR:
60 return "\"type\" : \"integer\", \"minimum\" : 0, \"maximum\" :" +
James Kuszmaul8e62b022022-03-22 09:33:25 -070061 NumToString(std::numeric_limits<uint8_t>::max());
Austin Schuh272c6132020-11-14 16:37:52 -080062 case BASE_TYPE_SHORT:
63 return "\"type\" : \"integer\", \"minimum\" : " +
64 NumToString(std::numeric_limits<int16_t>::min()) +
65 ", \"maximum\" : " +
66 NumToString(std::numeric_limits<int16_t>::max());
67 case BASE_TYPE_USHORT:
68 return "\"type\" : \"integer\", \"minimum\" : 0, \"maximum\" : " +
69 NumToString(std::numeric_limits<uint16_t>::max());
70 case BASE_TYPE_INT:
71 return "\"type\" : \"integer\", \"minimum\" : " +
72 NumToString(std::numeric_limits<int32_t>::min()) +
73 ", \"maximum\" : " +
74 NumToString(std::numeric_limits<int32_t>::max());
75 case BASE_TYPE_UINT:
76 return "\"type\" : \"integer\", \"minimum\" : 0, \"maximum\" : " +
77 NumToString(std::numeric_limits<uint32_t>::max());
78 case BASE_TYPE_LONG:
79 return "\"type\" : \"integer\", \"minimum\" : " +
80 NumToString(std::numeric_limits<int64_t>::min()) +
81 ", \"maximum\" : " +
82 NumToString(std::numeric_limits<int64_t>::max());
83 case BASE_TYPE_ULONG:
84 return "\"type\" : \"integer\", \"minimum\" : 0, \"maximum\" : " +
85 NumToString(std::numeric_limits<uint64_t>::max());
86 case BASE_TYPE_FLOAT:
87 case BASE_TYPE_DOUBLE: return "\"type\" : \"number\"";
88 case BASE_TYPE_STRING: return "\"type\" : \"string\"";
89 default: return "";
Austin Schuhe89fa2d2019-08-14 20:24:23 -070090 }
Austin Schuh272c6132020-11-14 16:37:52 -080091}
92
Austin Schuh2dd86a92022-09-14 21:19:23 -070093static std::string GenBaseType(const Type &type) {
Austin Schuh272c6132020-11-14 16:37:52 -080094 if (type.struct_def != nullptr) { return GenTypeRef(type.struct_def); }
95 if (type.enum_def != nullptr) { return GenTypeRef(type.enum_def); }
Austin Schuh58b9b472020-11-25 19:12:44 -080096 return GenType(type.base_type);
97}
98
Austin Schuh2dd86a92022-09-14 21:19:23 -070099static std::string GenArrayType(const Type &type) {
Austin Schuh58b9b472020-11-25 19:12:44 -0800100 std::string element_type;
101 if (type.struct_def != nullptr) {
102 element_type = GenTypeRef(type.struct_def);
103 } else if (type.enum_def != nullptr) {
104 element_type = GenTypeRef(type.enum_def);
105 } else {
106 element_type = GenType(type.element);
Austin Schuh272c6132020-11-14 16:37:52 -0800107 }
Austin Schuh58b9b472020-11-25 19:12:44 -0800108
109 return "\"type\" : \"array\", \"items\" : {" + element_type + "}";
Austin Schuh272c6132020-11-14 16:37:52 -0800110}
111
Austin Schuh2dd86a92022-09-14 21:19:23 -0700112static std::string GenType(const Type &type) {
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700113 switch (type.base_type) {
114 case BASE_TYPE_ARRAY: FLATBUFFERS_FALLTHROUGH(); // fall thru
115 case BASE_TYPE_VECTOR: {
Austin Schuh58b9b472020-11-25 19:12:44 -0800116 return GenArrayType(type);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700117 }
118 case BASE_TYPE_STRUCT: {
119 return GenTypeRef(type.struct_def);
120 }
121 case BASE_TYPE_UNION: {
122 std::string union_type_string("\"anyOf\": [");
123 const auto &union_types = type.enum_def->Vals();
124 for (auto ut = union_types.cbegin(); ut < union_types.cend(); ++ut) {
Austin Schuh272c6132020-11-14 16:37:52 -0800125 const auto &union_type = *ut;
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700126 if (union_type->union_type.base_type == BASE_TYPE_NONE) { continue; }
127 if (union_type->union_type.base_type == BASE_TYPE_STRUCT) {
128 union_type_string.append(
129 "{ " + GenTypeRef(union_type->union_type.struct_def) + " }");
130 }
131 if (union_type != *type.enum_def->Vals().rbegin()) {
132 union_type_string.append(",");
133 }
134 }
135 union_type_string.append("]");
136 return union_type_string;
137 }
138 case BASE_TYPE_UTYPE: return GenTypeRef(type.enum_def);
Austin Schuh272c6132020-11-14 16:37:52 -0800139 default: {
140 return GenBaseType(type);
141 }
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700142 }
143}
144
Austin Schuh2dd86a92022-09-14 21:19:23 -0700145} // namespace
146
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700147class JsonSchemaGenerator : public BaseGenerator {
148 private:
Austin Schuh272c6132020-11-14 16:37:52 -0800149 std::string code_;
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700150
151 public:
152 JsonSchemaGenerator(const Parser &parser, const std::string &path,
153 const std::string &file_name)
Austin Schuh272c6132020-11-14 16:37:52 -0800154 : BaseGenerator(parser, path, file_name, "", "", "json") {}
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700155
156 explicit JsonSchemaGenerator(const BaseGenerator &base_generator)
157 : BaseGenerator(base_generator) {}
158
Austin Schuh272c6132020-11-14 16:37:52 -0800159 std::string GeneratedFileName(const std::string &path,
160 const std::string &file_name,
161 const IDLOptions &options /* unused */) const {
162 (void)options;
163 return path + file_name + ".schema.json";
164 }
165
166 // If indentation is less than 0, that indicates we don't want any newlines
167 // either.
Austin Schuh58b9b472020-11-25 19:12:44 -0800168 std::string NewLine() const {
Austin Schuh272c6132020-11-14 16:37:52 -0800169 return parser_.opts.indent_step >= 0 ? "\n" : "";
170 }
171
Austin Schuh58b9b472020-11-25 19:12:44 -0800172 std::string Indent(int indent) const {
173 const auto num_spaces = indent * std::max(parser_.opts.indent_step, 0);
174 return std::string(num_spaces, ' ');
Austin Schuh272c6132020-11-14 16:37:52 -0800175 }
176
James Kuszmaul8e62b022022-03-22 09:33:25 -0700177 std::string PrepareDescription(
178 const std::vector<std::string> &comment_lines) {
179 std::string comment;
180 for (auto line_iterator = comment_lines.cbegin();
181 line_iterator != comment_lines.cend(); ++line_iterator) {
182 const auto &comment_line = *line_iterator;
183
184 // remove leading and trailing spaces from comment line
185 const auto start = std::find_if(comment_line.begin(), comment_line.end(),
186 [](char c) { return !isspace(c); });
187 const auto end =
188 std::find_if(comment_line.rbegin(), comment_line.rend(), [](char c) {
189 return !isspace(c);
190 }).base();
191 if (start < end) {
192 comment.append(start, end);
193 } else {
194 comment.append(comment_line);
195 }
196
197 if (line_iterator + 1 != comment_lines.cend()) comment.append("\n");
198 }
199 if (!comment.empty()) {
200 std::string description;
201 if (EscapeString(comment.c_str(), comment.length(), &description, true,
202 true)) {
203 return description;
204 }
205 return "";
206 }
207 return "";
208 }
209
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700210 bool generate() {
Austin Schuh272c6132020-11-14 16:37:52 -0800211 code_ = "";
James Kuszmaul8e62b022022-03-22 09:33:25 -0700212 if (parser_.root_struct_def_ == nullptr) {
213 std::cerr << "Error: Binary schema not generated, no root struct found\n";
214 return false;
215 }
Austin Schuh272c6132020-11-14 16:37:52 -0800216 code_ += "{" + NewLine();
217 code_ += Indent(1) +
218 "\"$schema\": \"https://json-schema.org/draft/2019-09/schema\"," +
219 NewLine();
220 code_ += Indent(1) + "\"definitions\": {" + NewLine();
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700221 for (auto e = parser_.enums_.vec.cbegin(); e != parser_.enums_.vec.cend();
222 ++e) {
Austin Schuh272c6132020-11-14 16:37:52 -0800223 code_ += Indent(2) + "\"" + GenFullName(*e) + "\" : {" + NewLine();
224 code_ += Indent(3) + GenType("string") + "," + NewLine();
Austin Schuh58b9b472020-11-25 19:12:44 -0800225 auto enumdef(Indent(3) + "\"enum\": [");
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700226 for (auto enum_value = (*e)->Vals().begin();
227 enum_value != (*e)->Vals().end(); ++enum_value) {
228 enumdef.append("\"" + (*enum_value)->name + "\"");
229 if (*enum_value != (*e)->Vals().back()) { enumdef.append(", "); }
230 }
231 enumdef.append("]");
Austin Schuh272c6132020-11-14 16:37:52 -0800232 code_ += enumdef + NewLine();
233 code_ += Indent(2) + "}," + NewLine(); // close type
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700234 }
235 for (auto s = parser_.structs_.vec.cbegin();
236 s != parser_.structs_.vec.cend(); ++s) {
237 const auto &structure = *s;
Austin Schuh272c6132020-11-14 16:37:52 -0800238 code_ += Indent(2) + "\"" + GenFullName(structure) + "\" : {" + NewLine();
239 code_ += Indent(3) + GenType("object") + "," + NewLine();
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700240 const auto &comment_lines = structure->doc_comment;
James Kuszmaul8e62b022022-03-22 09:33:25 -0700241 auto comment = PrepareDescription(comment_lines);
242 if (comment != "") {
243 code_ += Indent(3) + "\"description\" : " + comment + "," + NewLine();
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700244 }
James Kuszmaul8e62b022022-03-22 09:33:25 -0700245
Austin Schuh272c6132020-11-14 16:37:52 -0800246 code_ += Indent(3) + "\"properties\" : {" + NewLine();
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700247
248 const auto &properties = structure->fields.vec;
249 for (auto prop = properties.cbegin(); prop != properties.cend(); ++prop) {
250 const auto &property = *prop;
251 std::string arrayInfo = "";
252 if (IsArray(property->value.type)) {
Austin Schuh272c6132020-11-14 16:37:52 -0800253 arrayInfo = "," + NewLine() + Indent(8) + "\"minItems\": " +
Austin Schuh58b9b472020-11-25 19:12:44 -0800254 NumToString(property->value.type.fixed_length) + "," +
255 NewLine() + Indent(8) + "\"maxItems\": " +
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700256 NumToString(property->value.type.fixed_length);
257 }
Austin Schuh272c6132020-11-14 16:37:52 -0800258 std::string deprecated_info = "";
259 if (property->deprecated) {
Austin Schuh58b9b472020-11-25 19:12:44 -0800260 deprecated_info =
James Kuszmaul8e62b022022-03-22 09:33:25 -0700261 "," + NewLine() + Indent(8) + "\"deprecated\" : true";
Austin Schuh272c6132020-11-14 16:37:52 -0800262 }
263 std::string typeLine = Indent(4) + "\"" + property->name + "\"";
264 typeLine += " : {" + NewLine() + Indent(8);
265 typeLine += GenType(property->value.type);
266 typeLine += arrayInfo;
267 typeLine += deprecated_info;
James Kuszmaul8e62b022022-03-22 09:33:25 -0700268 auto description = PrepareDescription(property->doc_comment);
269 if (description != "") {
270 typeLine +=
271 "," + NewLine() + Indent(8) + "\"description\" : " + description;
272 }
273
Austin Schuh272c6132020-11-14 16:37:52 -0800274 typeLine += NewLine() + Indent(7) + "}";
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700275 if (property != properties.back()) { typeLine.append(","); }
Austin Schuh272c6132020-11-14 16:37:52 -0800276 code_ += typeLine + NewLine();
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700277 }
Austin Schuh272c6132020-11-14 16:37:52 -0800278 code_ += Indent(3) + "}," + NewLine(); // close properties
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700279
280 std::vector<FieldDef *> requiredProperties;
281 std::copy_if(properties.begin(), properties.end(),
282 back_inserter(requiredProperties),
James Kuszmaul8e62b022022-03-22 09:33:25 -0700283 [](FieldDef const *prop) { return prop->IsRequired(); });
Austin Schuh58b9b472020-11-25 19:12:44 -0800284 if (!requiredProperties.empty()) {
285 auto required_string(Indent(3) + "\"required\" : [");
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700286 for (auto req_prop = requiredProperties.cbegin();
287 req_prop != requiredProperties.cend(); ++req_prop) {
288 required_string.append("\"" + (*req_prop)->name + "\"");
289 if (*req_prop != requiredProperties.back()) {
290 required_string.append(", ");
291 }
292 }
293 required_string.append("],");
Austin Schuh272c6132020-11-14 16:37:52 -0800294 code_ += required_string + NewLine();
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700295 }
Austin Schuh272c6132020-11-14 16:37:52 -0800296 code_ += Indent(3) + "\"additionalProperties\" : false" + NewLine();
Austin Schuh58b9b472020-11-25 19:12:44 -0800297 auto closeType(Indent(2) + "}");
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700298 if (*s != parser_.structs_.vec.back()) { closeType.append(","); }
Austin Schuh272c6132020-11-14 16:37:52 -0800299 code_ += closeType + NewLine(); // close type
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700300 }
Austin Schuh272c6132020-11-14 16:37:52 -0800301 code_ += Indent(1) + "}," + NewLine(); // close definitions
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700302
303 // mark root type
Austin Schuh272c6132020-11-14 16:37:52 -0800304 code_ += Indent(1) + "\"$ref\" : \"#/definitions/" +
305 GenFullName(parser_.root_struct_def_) + "\"" + NewLine();
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700306
Austin Schuh272c6132020-11-14 16:37:52 -0800307 code_ += "}" + NewLine(); // close schema root
308 return true;
309 }
310
Austin Schuh58b9b472020-11-25 19:12:44 -0800311 bool save() const {
James Kuszmaul8e62b022022-03-22 09:33:25 -0700312 const auto file_path = GeneratedFileName(path_, file_name_, parser_.opts);
Austin Schuh272c6132020-11-14 16:37:52 -0800313 return SaveFile(file_path.c_str(), code_, false);
314 }
315
Austin Schuh58b9b472020-11-25 19:12:44 -0800316 const std::string getJson() { return code_; }
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700317};
318} // namespace jsons
319
320bool GenerateJsonSchema(const Parser &parser, const std::string &path,
321 const std::string &file_name) {
322 jsons::JsonSchemaGenerator generator(parser, path, file_name);
Austin Schuh272c6132020-11-14 16:37:52 -0800323 if (!generator.generate()) { return false; }
324 return generator.save();
325}
326
327bool GenerateJsonSchema(const Parser &parser, std::string *json) {
328 jsons::JsonSchemaGenerator generator(parser, "", "");
329 if (!generator.generate()) { return false; }
330 *json = generator.getJson();
331 return true;
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700332}
333} // namespace flatbuffers