[C++] Refactor to conform to Google C++ style guide (#5608)
[platform/upstream/flatbuffers.git] / src / idl_gen_json_schema.cpp
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 #include <iostream>
18
19 #include "flatbuffers/code_generators.h"
20 #include "flatbuffers/idl.h"
21 #include "flatbuffers/util.h"
22
23 namespace flatbuffers {
24
25 static std::string GeneratedFileName(const std::string &path,
26                                      const std::string &file_name) {
27   return path + file_name + ".schema.json";
28 }
29
30 namespace jsons {
31
32 std::string GenNativeType(BaseType type) {
33   switch (type) {
34     case BASE_TYPE_BOOL: return "boolean";
35     case BASE_TYPE_CHAR:
36     case BASE_TYPE_UCHAR:
37     case BASE_TYPE_SHORT:
38     case BASE_TYPE_USHORT:
39     case BASE_TYPE_INT:
40     case BASE_TYPE_UINT:
41     case BASE_TYPE_LONG:
42     case BASE_TYPE_ULONG:
43     case BASE_TYPE_FLOAT:
44     case BASE_TYPE_DOUBLE: return "number";
45     case BASE_TYPE_STRING: return "string";
46     case BASE_TYPE_ARRAY: return "array";
47     default: return "";
48   }
49 }
50
51 template<class T> std::string GenFullName(const T *enum_def) {
52   std::string full_name;
53   const auto &name_spaces = enum_def->defined_namespace->components;
54   for (auto ns = name_spaces.cbegin(); ns != name_spaces.cend(); ++ns) {
55     full_name.append(*ns + "_");
56   }
57   full_name.append(enum_def->name);
58   return full_name;
59 }
60
61 template<class T> std::string GenTypeRef(const T *enum_def) {
62   return "\"$ref\" : \"#/definitions/" + GenFullName(enum_def) + "\"";
63 }
64
65 std::string GenType(const std::string &name) {
66   return "\"type\" : \"" + name + "\"";
67 }
68
69 std::string GenType(const Type &type) {
70   if (type.enum_def != nullptr && !type.enum_def->is_union) {
71     // it is a reference to an enum type
72     return GenTypeRef(type.enum_def);
73   }
74   switch (type.base_type) {
75     case BASE_TYPE_ARRAY: FLATBUFFERS_FALLTHROUGH();  // fall thru
76     case BASE_TYPE_VECTOR: {
77       std::string typeline;
78       typeline.append("\"type\" : \"array\", \"items\" : { ");
79       if (type.element == BASE_TYPE_STRUCT) {
80         typeline.append(GenTypeRef(type.struct_def));
81       } else {
82         typeline.append(GenType(GenNativeType(type.element)));
83       }
84       typeline.append(" }");
85       return typeline;
86     }
87     case BASE_TYPE_STRUCT: {
88       return GenTypeRef(type.struct_def);
89     }
90     case BASE_TYPE_UNION: {
91       std::string union_type_string("\"anyOf\": [");
92       const auto &union_types = type.enum_def->Vals();
93       for (auto ut = union_types.cbegin(); ut < union_types.cend(); ++ut) {
94         auto &union_type = *ut;
95         if (union_type->union_type.base_type == BASE_TYPE_NONE) { continue; }
96         if (union_type->union_type.base_type == BASE_TYPE_STRUCT) {
97           union_type_string.append(
98               "{ " + GenTypeRef(union_type->union_type.struct_def) + " }");
99         }
100         if (union_type != *type.enum_def->Vals().rbegin()) {
101           union_type_string.append(",");
102         }
103       }
104       union_type_string.append("]");
105       return union_type_string;
106     }
107     case BASE_TYPE_UTYPE: return GenTypeRef(type.enum_def);
108     default: return GenType(GenNativeType(type.base_type));
109   }
110 }
111
112 class JsonSchemaGenerator : public BaseGenerator {
113  private:
114   CodeWriter code_;
115
116  public:
117   JsonSchemaGenerator(const Parser &parser, const std::string &path,
118                       const std::string &file_name)
119       : BaseGenerator(parser, path, file_name, "", "") {}
120
121   explicit JsonSchemaGenerator(const BaseGenerator &base_generator)
122       : BaseGenerator(base_generator) {}
123
124   bool generate() {
125     code_.Clear();
126     code_ += "{";
127     code_ += "  \"$schema\": \"http://json-schema.org/draft-04/schema#\",";
128     code_ += "  \"definitions\": {";
129     for (auto e = parser_.enums_.vec.cbegin(); e != parser_.enums_.vec.cend();
130          ++e) {
131       code_ += "    \"" + GenFullName(*e) + "\" : {";
132       code_ += "      " + GenType("string") + ",";
133       std::string enumdef("      \"enum\": [");
134       for (auto enum_value = (*e)->Vals().begin();
135            enum_value != (*e)->Vals().end(); ++enum_value) {
136         enumdef.append("\"" + (*enum_value)->name + "\"");
137         if (*enum_value != (*e)->Vals().back()) { enumdef.append(", "); }
138       }
139       enumdef.append("]");
140       code_ += enumdef;
141       code_ += "    },";  // close type
142     }
143     for (auto s = parser_.structs_.vec.cbegin();
144          s != parser_.structs_.vec.cend(); ++s) {
145       const auto &structure = *s;
146       code_ += "    \"" + GenFullName(structure) + "\" : {";
147       code_ += "      " + GenType("object") + ",";
148       std::string comment;
149       const auto &comment_lines = structure->doc_comment;
150       for (auto comment_line = comment_lines.cbegin();
151            comment_line != comment_lines.cend(); ++comment_line) {
152         comment.append(*comment_line);
153       }
154       if (comment.size() > 0) {
155         code_ += "      \"description\" : \"" + comment + "\",";
156       }
157       code_ += "      \"properties\" : {";
158
159       const auto &properties = structure->fields.vec;
160       for (auto prop = properties.cbegin(); prop != properties.cend(); ++prop) {
161         const auto &property = *prop;
162         std::string arrayInfo = "";
163         if (IsArray(property->value.type)) {
164           arrayInfo = ",\n                \"minItems\": " +
165                       NumToString(property->value.type.fixed_length) +
166                       ",\n                \"maxItems\": " +
167                       NumToString(property->value.type.fixed_length);
168         }
169         std::string typeLine =
170             "        \"" + property->name + "\" : {\n" + "                " +
171             GenType(property->value.type) + arrayInfo + "\n              }";
172         if (property != properties.back()) { typeLine.append(","); }
173         code_ += typeLine;
174       }
175       code_ += "      },";  // close properties
176
177       std::vector<FieldDef *> requiredProperties;
178       std::copy_if(properties.begin(), properties.end(),
179                    back_inserter(requiredProperties),
180                    [](FieldDef const *prop) { return prop->required; });
181       if (requiredProperties.size() > 0) {
182         std::string required_string("      \"required\" : [");
183         for (auto req_prop = requiredProperties.cbegin();
184              req_prop != requiredProperties.cend(); ++req_prop) {
185           required_string.append("\"" + (*req_prop)->name + "\"");
186           if (*req_prop != requiredProperties.back()) {
187             required_string.append(", ");
188           }
189         }
190         required_string.append("],");
191         code_ += required_string;
192       }
193       code_ += "      \"additionalProperties\" : false";
194       std::string closeType("    }");
195       if (*s != parser_.structs_.vec.back()) { closeType.append(","); }
196       code_ += closeType;  // close type
197     }
198     code_ += "  },";  // close definitions
199
200     // mark root type
201     code_ += "  \"$ref\" : \"#/definitions/" +
202              GenFullName(parser_.root_struct_def_) + "\"";
203
204     code_ += "}";  // close schema root
205     const std::string file_path = GeneratedFileName(path_, file_name_);
206     const std::string final_code = code_.ToString();
207     return SaveFile(file_path.c_str(), final_code, false);
208   }
209 };
210 }  // namespace jsons
211
212 bool GenerateJsonSchema(const Parser &parser, const std::string &path,
213                         const std::string &file_name) {
214   jsons::JsonSchemaGenerator generator(parser, path, file_name);
215   return generator.generate();
216 }
217 }  // namespace flatbuffers