blob: a321b8920b805491a69c5bd1dc98be1e5b53254f [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 Schuhe89fa2d2019-08-14 20:24:23 -070027template<class T> std::string GenFullName(const T *enum_def) {
28 std::string full_name;
29 const auto &name_spaces = enum_def->defined_namespace->components;
30 for (auto ns = name_spaces.cbegin(); ns != name_spaces.cend(); ++ns) {
31 full_name.append(*ns + "_");
32 }
33 full_name.append(enum_def->name);
34 return full_name;
35}
36
37template<class T> std::string GenTypeRef(const T *enum_def) {
38 return "\"$ref\" : \"#/definitions/" + GenFullName(enum_def) + "\"";
39}
40
41std::string GenType(const std::string &name) {
42 return "\"type\" : \"" + name + "\"";
43}
44
Austin Schuh272c6132020-11-14 16:37:52 -080045std::string GenType(BaseType type) {
46 switch (type) {
47 case BASE_TYPE_BOOL: return "\"type\" : \"boolean\"";
48 case BASE_TYPE_CHAR:
49 return "\"type\" : \"integer\", \"minimum\" : " +
50 NumToString(std::numeric_limits<int8_t>::min()) +
51 ", \"maximum\" : " +
52 NumToString(std::numeric_limits<int8_t>::max()) + "\"";
53 case BASE_TYPE_UCHAR:
54 return "\"type\" : \"integer\", \"minimum\" : 0, \"maximum\" :" +
55 NumToString(std::numeric_limits<uint8_t>::max()) + "\"";
56 case BASE_TYPE_SHORT:
57 return "\"type\" : \"integer\", \"minimum\" : " +
58 NumToString(std::numeric_limits<int16_t>::min()) +
59 ", \"maximum\" : " +
60 NumToString(std::numeric_limits<int16_t>::max());
61 case BASE_TYPE_USHORT:
62 return "\"type\" : \"integer\", \"minimum\" : 0, \"maximum\" : " +
63 NumToString(std::numeric_limits<uint16_t>::max());
64 case BASE_TYPE_INT:
65 return "\"type\" : \"integer\", \"minimum\" : " +
66 NumToString(std::numeric_limits<int32_t>::min()) +
67 ", \"maximum\" : " +
68 NumToString(std::numeric_limits<int32_t>::max());
69 case BASE_TYPE_UINT:
70 return "\"type\" : \"integer\", \"minimum\" : 0, \"maximum\" : " +
71 NumToString(std::numeric_limits<uint32_t>::max());
72 case BASE_TYPE_LONG:
73 return "\"type\" : \"integer\", \"minimum\" : " +
74 NumToString(std::numeric_limits<int64_t>::min()) +
75 ", \"maximum\" : " +
76 NumToString(std::numeric_limits<int64_t>::max());
77 case BASE_TYPE_ULONG:
78 return "\"type\" : \"integer\", \"minimum\" : 0, \"maximum\" : " +
79 NumToString(std::numeric_limits<uint64_t>::max());
80 case BASE_TYPE_FLOAT:
81 case BASE_TYPE_DOUBLE: return "\"type\" : \"number\"";
82 case BASE_TYPE_STRING: return "\"type\" : \"string\"";
83 default: return "";
Austin Schuhe89fa2d2019-08-14 20:24:23 -070084 }
Austin Schuh272c6132020-11-14 16:37:52 -080085}
86
87std::string GenBaseType(const Type &type) {
88 if (type.struct_def != nullptr) { return GenTypeRef(type.struct_def); }
89 if (type.enum_def != nullptr) { return GenTypeRef(type.enum_def); }
90 if (IsArray(type) || IsVector(type)) {
91 return "\"type\" : \"array\", \"items\" : {" + GenType(type.element) + "}";
92 }
93 return GenType(type.base_type);
94}
95
96std::string GenType(const Type &type) {
Austin Schuhe89fa2d2019-08-14 20:24:23 -070097 switch (type.base_type) {
98 case BASE_TYPE_ARRAY: FLATBUFFERS_FALLTHROUGH(); // fall thru
99 case BASE_TYPE_VECTOR: {
Austin Schuh272c6132020-11-14 16:37:52 -0800100 return GenBaseType(type);
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700101 }
102 case BASE_TYPE_STRUCT: {
103 return GenTypeRef(type.struct_def);
104 }
105 case BASE_TYPE_UNION: {
106 std::string union_type_string("\"anyOf\": [");
107 const auto &union_types = type.enum_def->Vals();
108 for (auto ut = union_types.cbegin(); ut < union_types.cend(); ++ut) {
Austin Schuh272c6132020-11-14 16:37:52 -0800109 const auto &union_type = *ut;
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700110 if (union_type->union_type.base_type == BASE_TYPE_NONE) { continue; }
111 if (union_type->union_type.base_type == BASE_TYPE_STRUCT) {
112 union_type_string.append(
113 "{ " + GenTypeRef(union_type->union_type.struct_def) + " }");
114 }
115 if (union_type != *type.enum_def->Vals().rbegin()) {
116 union_type_string.append(",");
117 }
118 }
119 union_type_string.append("]");
120 return union_type_string;
121 }
122 case BASE_TYPE_UTYPE: return GenTypeRef(type.enum_def);
Austin Schuh272c6132020-11-14 16:37:52 -0800123 default: {
124 return GenBaseType(type);
125 }
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700126 }
127}
128
129class JsonSchemaGenerator : public BaseGenerator {
130 private:
Austin Schuh272c6132020-11-14 16:37:52 -0800131 std::string code_;
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700132
133 public:
134 JsonSchemaGenerator(const Parser &parser, const std::string &path,
135 const std::string &file_name)
Austin Schuh272c6132020-11-14 16:37:52 -0800136 : BaseGenerator(parser, path, file_name, "", "", "json") {}
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700137
138 explicit JsonSchemaGenerator(const BaseGenerator &base_generator)
139 : BaseGenerator(base_generator) {}
140
Austin Schuh272c6132020-11-14 16:37:52 -0800141 std::string GeneratedFileName(const std::string &path,
142 const std::string &file_name,
143 const IDLOptions &options /* unused */) const {
144 (void)options;
145 return path + file_name + ".schema.json";
146 }
147
148 // If indentation is less than 0, that indicates we don't want any newlines
149 // either.
150 const std::string NewLine() {
151 return parser_.opts.indent_step >= 0 ? "\n" : "";
152 }
153
154 const std::string Indent(int indent) {
155 std::string indentation = "";
156 return indentation.append(indent * std::max(parser_.opts.indent_step, 0), ' ');
157 }
158
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700159 bool generate() {
Austin Schuh272c6132020-11-14 16:37:52 -0800160 code_ = "";
161 if (parser_.root_struct_def_ == nullptr) { return false; }
162 code_ += "{" + NewLine();
163 code_ += Indent(1) +
164 "\"$schema\": \"https://json-schema.org/draft/2019-09/schema\"," +
165 NewLine();
166 code_ += Indent(1) + "\"definitions\": {" + NewLine();
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700167 for (auto e = parser_.enums_.vec.cbegin(); e != parser_.enums_.vec.cend();
168 ++e) {
Austin Schuh272c6132020-11-14 16:37:52 -0800169 code_ += Indent(2) + "\"" + GenFullName(*e) + "\" : {" + NewLine();
170 code_ += Indent(3) + GenType("string") + "," + NewLine();
171 std::string enumdef(Indent(3) + "\"enum\": [");
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700172 for (auto enum_value = (*e)->Vals().begin();
173 enum_value != (*e)->Vals().end(); ++enum_value) {
174 enumdef.append("\"" + (*enum_value)->name + "\"");
175 if (*enum_value != (*e)->Vals().back()) { enumdef.append(", "); }
176 }
177 enumdef.append("]");
Austin Schuh272c6132020-11-14 16:37:52 -0800178 code_ += enumdef + NewLine();
179 code_ += Indent(2) + "}," + NewLine(); // close type
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700180 }
181 for (auto s = parser_.structs_.vec.cbegin();
182 s != parser_.structs_.vec.cend(); ++s) {
183 const auto &structure = *s;
Austin Schuh272c6132020-11-14 16:37:52 -0800184 code_ += Indent(2) + "\"" + GenFullName(structure) + "\" : {" + NewLine();
185 code_ += Indent(3) + GenType("object") + "," + NewLine();
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700186 std::string comment;
187 const auto &comment_lines = structure->doc_comment;
188 for (auto comment_line = comment_lines.cbegin();
189 comment_line != comment_lines.cend(); ++comment_line) {
190 comment.append(*comment_line);
191 }
192 if (comment.size() > 0) {
Austin Schuh272c6132020-11-14 16:37:52 -0800193 std::string description;
194 if (!EscapeString(comment.c_str(), comment.length(), &description, true,
195 true)) {
196 return false;
197 }
198 code_ +=
199 Indent(3) + "\"description\" : " + description + "," + NewLine();
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700200 }
Austin Schuh272c6132020-11-14 16:37:52 -0800201 code_ += Indent(3) + "\"properties\" : {" + NewLine();
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700202
203 const auto &properties = structure->fields.vec;
204 for (auto prop = properties.cbegin(); prop != properties.cend(); ++prop) {
205 const auto &property = *prop;
206 std::string arrayInfo = "";
207 if (IsArray(property->value.type)) {
Austin Schuh272c6132020-11-14 16:37:52 -0800208 arrayInfo = "," + NewLine() + Indent(8) + "\"minItems\": " +
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700209 NumToString(property->value.type.fixed_length) +
Austin Schuh272c6132020-11-14 16:37:52 -0800210 "," + NewLine() + Indent(8) + "\"maxItems\": " +
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700211 NumToString(property->value.type.fixed_length);
212 }
Austin Schuh272c6132020-11-14 16:37:52 -0800213 std::string deprecated_info = "";
214 if (property->deprecated) {
215 deprecated_info = "," + NewLine() + Indent(8) + "\"deprecated\" : true,";
216 }
217 std::string typeLine = Indent(4) + "\"" + property->name + "\"";
218 typeLine += " : {" + NewLine() + Indent(8);
219 typeLine += GenType(property->value.type);
220 typeLine += arrayInfo;
221 typeLine += deprecated_info;
222 typeLine += NewLine() + Indent(7) + "}";
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700223 if (property != properties.back()) { typeLine.append(","); }
Austin Schuh272c6132020-11-14 16:37:52 -0800224 code_ += typeLine + NewLine();
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700225 }
Austin Schuh272c6132020-11-14 16:37:52 -0800226 code_ += Indent(3) + "}," + NewLine(); // close properties
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700227
228 std::vector<FieldDef *> requiredProperties;
229 std::copy_if(properties.begin(), properties.end(),
230 back_inserter(requiredProperties),
231 [](FieldDef const *prop) { return prop->required; });
232 if (requiredProperties.size() > 0) {
Austin Schuh272c6132020-11-14 16:37:52 -0800233 std::string required_string(Indent(3) + "\"required\" : [");
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700234 for (auto req_prop = requiredProperties.cbegin();
235 req_prop != requiredProperties.cend(); ++req_prop) {
236 required_string.append("\"" + (*req_prop)->name + "\"");
237 if (*req_prop != requiredProperties.back()) {
238 required_string.append(", ");
239 }
240 }
241 required_string.append("],");
Austin Schuh272c6132020-11-14 16:37:52 -0800242 code_ += required_string + NewLine();
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700243 }
Austin Schuh272c6132020-11-14 16:37:52 -0800244 code_ += Indent(3) + "\"additionalProperties\" : false" + NewLine();
245 std::string closeType(Indent(2) + "}");
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700246 if (*s != parser_.structs_.vec.back()) { closeType.append(","); }
Austin Schuh272c6132020-11-14 16:37:52 -0800247 code_ += closeType + NewLine(); // close type
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700248 }
Austin Schuh272c6132020-11-14 16:37:52 -0800249 code_ += Indent(1) + "}," + NewLine(); // close definitions
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700250
251 // mark root type
Austin Schuh272c6132020-11-14 16:37:52 -0800252 code_ += Indent(1) + "\"$ref\" : \"#/definitions/" +
253 GenFullName(parser_.root_struct_def_) + "\"" + NewLine();
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700254
Austin Schuh272c6132020-11-14 16:37:52 -0800255 code_ += "}" + NewLine(); // close schema root
256 return true;
257 }
258
259 bool save() {
260 const std::string file_path =
261 GeneratedFileName(path_, file_name_, parser_.opts);
262 return SaveFile(file_path.c_str(), code_, false);
263 }
264
265 const std::string getJson() {
266 return code_;
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700267 }
268};
269} // namespace jsons
270
271bool GenerateJsonSchema(const Parser &parser, const std::string &path,
272 const std::string &file_name) {
273 jsons::JsonSchemaGenerator generator(parser, path, file_name);
Austin Schuh272c6132020-11-14 16:37:52 -0800274 if (!generator.generate()) { return false; }
275 return generator.save();
276}
277
278bool GenerateJsonSchema(const Parser &parser, std::string *json) {
279 jsons::JsonSchemaGenerator generator(parser, "", "");
280 if (!generator.generate()) { return false; }
281 *json = generator.getJson();
282 return true;
Austin Schuhe89fa2d2019-08-14 20:24:23 -0700283}
284} // namespace flatbuffers