Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[TS] Fix reserved words as arguments (#6955) #6956

Merged
merged 14 commits into from
Dec 6, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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