From 87934ecf395bc503b48f09c821955f4d8e82a0ed Mon Sep 17 00:00:00 2001 From: yuyi Date: Sun, 5 Sep 2021 00:51:45 +0800 Subject: [PATCH] cgen: fix variable name are 'array' or 'string' (fix #10991 #11343) (#11378) --- vlib/v/gen/c/cgen.v | 20 ++++++++++++------- .../reserved_keywords_array_and_string_test.v | 13 ++++++++++++ 2 files changed, 26 insertions(+), 7 deletions(-) create mode 100644 vlib/v/tests/reserved_keywords_array_and_string_test.v diff --git a/vlib/v/gen/c/cgen.v b/vlib/v/gen/c/cgen.v index 35df5a93d3..6b47b4108b 100644 --- a/vlib/v/gen/c/cgen.v +++ b/vlib/v/gen/c/cgen.v @@ -15,12 +15,12 @@ import v.depgraph const ( // NB: some of the words in c_reserved, are not reserved in C, // but are in C++, or have special meaning in V, thus need escaping too. - c_reserved = ['auto', 'break', 'calloc', 'case', 'char', 'class', 'const', 'continue', - 'default', 'delete', 'do', 'double', 'else', 'enum', 'error', 'exit', 'export', 'extern', - 'float', 'for', 'free', 'goto', 'if', 'inline', 'int', 'link', 'long', 'malloc', 'namespace', - 'new', 'panic', 'register', 'restrict', 'return', 'short', 'signed', 'sizeof', 'static', - 'struct', 'switch', 'typedef', 'typename', 'union', 'unix', 'unsigned', 'void', 'volatile', - 'while', 'template', 'stdout', 'stdin', 'stderr'] + c_reserved = ['array', 'auto', 'break', 'calloc', 'case', 'char', 'class', 'const', + 'continue', 'default', 'delete', 'do', 'double', 'else', 'enum', 'error', 'exit', 'export', + 'extern', 'float', 'for', 'free', 'goto', 'if', 'inline', 'int', 'link', 'long', 'malloc', + 'namespace', 'new', 'panic', 'register', 'restrict', 'return', 'short', 'signed', 'sizeof', + 'static', 'string', 'struct', 'switch', 'typedef', 'typename', 'union', 'unix', 'unsigned', + 'void', 'volatile', 'while', 'template', 'stdout', 'stdin', 'stderr'] c_reserved_map = string_array_to_map(c_reserved) // same order as in token.Kind cmp_str = ['eq', 'ne', 'gt', 'lt', 'ge', 'le'] @@ -1493,7 +1493,13 @@ fn (mut g Gen) stmt(node ast.Stmt) { g.sql_stmt(node) } ast.StructDecl { - name := if node.language == .c { util.no_dots(node.name) } else { c_name(node.name) } + name := if node.language == .c { + util.no_dots(node.name) + } else if node.name in ['array', 'string'] { + node.name + } else { + c_name(node.name) + } // TODO For some reason, build fails with autofree with this line // as it's only informative, comment it for now // g.gen_attrs(node.attrs) diff --git a/vlib/v/tests/reserved_keywords_array_and_string_test.v b/vlib/v/tests/reserved_keywords_array_and_string_test.v new file mode 100644 index 0000000000..8bf47f2e6a --- /dev/null +++ b/vlib/v/tests/reserved_keywords_array_and_string_test.v @@ -0,0 +1,13 @@ +fn test_reserved_keywords_array_and_string() { + array := [1, 2, 3, 4] + mut res1 := array.map(it * 3) + mut res2 := array.filter(it > 2) + println(res1) + assert res1 == [3, 6, 9, 12] + println(res2) + assert res2 == [3, 4] + + string := 'hello' + println(string) + assert string == 'hello' +}