From 06eb3e4dbc5e3f3171afd2e71688823877a92027 Mon Sep 17 00:00:00 2001 From: TSUYUSATO Kitsune Date: Wed, 1 Sep 2021 13:09:51 +0900 Subject: [PATCH] Reject a hash literal having both of 'key => value' and 'key: value' entry Fix #11074 --- spec/compiler/parser/parser_spec.cr | 1 + src/compiler/crystal/syntax/parser.cr | 3 ++- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/spec/compiler/parser/parser_spec.cr b/spec/compiler/parser/parser_spec.cr index c5cfbf831fcd..930f1a76fcb9 100644 --- a/spec/compiler/parser/parser_spec.cr +++ b/spec/compiler/parser/parser_spec.cr @@ -1115,6 +1115,7 @@ module Crystal it_parses "{1 => 2, 3 => 4}", HashLiteral.new([HashLiteral::Entry.new(1.int32, 2.int32), HashLiteral::Entry.new(3.int32, 4.int32)]) it_parses %({A::B => 1, C::D => 2}), HashLiteral.new([HashLiteral::Entry.new(Path.new(["A", "B"]), 1.int32), HashLiteral::Entry.new(Path.new(["C", "D"]), 2.int32)]) + assert_syntax_error %({"foo" => 1, "bar": 2}), "can't use 'key: value' syntax in a hash literal" it_parses "{a: 1}", NamedTupleLiteral.new([NamedTupleLiteral::Entry.new("a", 1.int32)]) it_parses "{a: 1, b: 2}", NamedTupleLiteral.new([NamedTupleLiteral::Entry.new("a", 1.int32), NamedTupleLiteral::Entry.new("b", 2.int32)]) diff --git a/src/compiler/crystal/syntax/parser.cr b/src/compiler/crystal/syntax/parser.cr index 539886d9344c..0874056e448e 100644 --- a/src/compiler/crystal/syntax/parser.cr +++ b/src/compiler/crystal/syntax/parser.cr @@ -2419,10 +2419,11 @@ module Crystal end while @token.type != :"}" + key_loc = @token.location key = parse_op_assign_no_control skip_space_or_newline if @token.type == :":" && key.is_a?(StringLiteral) - # Nothing: it's a string key + raise "can't use 'key: value' syntax in a hash literal", key_loc else check :"=>" end