Skip to content

Commit

Permalink
[TS] Fix reserved words as arguments (#6955) (#6956)
Browse files Browse the repository at this point in the history
* Fix C/C++ Create<Type>Direct with sorted vectors

If a struct has a key the vector has to be sorted. To sort the vector
you can't use "const".

* Changes due to code review

* Improve code readability

* Add generate of JSON schema to string to lib

* option indent_step is supported

* Remove unused variables

* Fix break in test

* Fix style to be consistent with rest of the code

* [TS] Fix reserved words as arguments (#6955)
  • Loading branch information
tira-misu committed Dec 6, 2021
1 parent e57f4ab commit 18538c4
Showing 1 changed file with 71 additions and 4 deletions.
75 changes: 71 additions & 4 deletions src/idl_gen_ts.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,65 @@ class TsGenerator : public BaseGenerator {

TsGenerator(const Parser &parser, const std::string &path,
const std::string &file_name)
: BaseGenerator(parser, path, file_name, "", ".", "ts") {}
: BaseGenerator(parser, path, file_name, "", ".", "ts") {
// clang-format off

// List of keywords retrieved from here:
// https://github.com/microsoft/TypeScript/issues/2536
// One per line to ease comparisons to that list are easier
static const char *const keywords[] = {
"break",
"case",
"catch",
"class",
"const",
"continue",
"debugger",
"default",
"delete",
"do",
"else",
"enum",
"export",
"extends",
"false",
"finally",
"for",
"function",
"if",
"import",
"in",
"instanceof",
"new",
"null",
"return",
"super",
"switch",
"this",
"throw",
"true",
"try",
"typeof",
"var",
"void",
"while",
"with",
"as",
"implements",
"interface",
"let",
"package",
"private",
"protected",
"public",
"static",
"yield",
nullptr,
// clang-format on
};

for (auto kw = keywords; *kw; kw++) keywords_.insert(*kw);
}
bool generate() {
generateEnums();
generateStructs();
Expand Down Expand Up @@ -81,6 +139,12 @@ class TsGenerator : public BaseGenerator {
}

private:
std::unordered_set<std::string> keywords_;

std::string EscapeKeyword(const std::string &name) const {
return keywords_.find(name) == keywords_.end() ? name : name + "_";
}

import_set imports_all_;

// Generate code for all enums.
Expand Down Expand Up @@ -1581,10 +1645,13 @@ class TsGenerator : public BaseGenerator {
allowNull && field.IsOptional());
}

static std::string GetArgName(const FieldDef &field) {
std::string GetArgName(const FieldDef &field) {
auto argname = MakeCamel(field.name, false);
if (!IsScalar(field.value.type.base_type)) { argname += "Offset"; }

if (!IsScalar(field.value.type.base_type)) {
argname += "Offset";
} else {
argname = EscapeKeyword(argname);
}
return argname;
}

Expand Down

0 comments on commit 18538c4

Please sign in to comment.