From ac2f7208ccf25d783cab9a140c025664f94b2544 Mon Sep 17 00:00:00 2001 From: Caspian Baska Date: Sun, 23 Oct 2022 19:44:04 +0800 Subject: [PATCH] Parser: Fix restrict grammar for name and supertype in type def (#12622) --- spec/compiler/parser/parser_spec.cr | 11 +++++++++++ src/compiler/crystal/syntax/parser.cr | 10 ++++++++++ 2 files changed, 21 insertions(+) diff --git a/spec/compiler/parser/parser_spec.cr b/spec/compiler/parser/parser_spec.cr index b5e0a0301fc6..581b1e9dbe15 100644 --- a/spec/compiler/parser/parser_spec.cr +++ b/spec/compiler/parser/parser_spec.cr @@ -253,6 +253,17 @@ module Crystal assert_syntax_error "foo { |(#{kw})| }", "cannot use '#{kw}' as a block parameter name", 1, 9 end + describe "literals in class definitions" do + # #11209 + %w("a" 'a' [1] {1} {|a|a} ->{} ->(x : Bar){} :Bar :bar %x() %w() %()).each do |invalid| + assert_syntax_error "class Foo#{invalid}; end" + assert_syntax_error "class Foo#{invalid} < Baz; end" + assert_syntax_error "class Foo#{invalid} < self; end" + assert_syntax_error "class Foo < Baz#{invalid}; end" + assert_syntax_error "class Foo < self#{invalid}; end" + end + end + it_parses "def self.foo\n1\nend", Def.new("foo", body: 1.int32, receiver: "self".var) it_parses "def self.foo()\n1\nend", Def.new("foo", body: 1.int32, receiver: "self".var) it_parses "def self.foo=\n1\nend", Def.new("foo=", body: 1.int32, receiver: "self".var) diff --git a/src/compiler/crystal/syntax/parser.cr b/src/compiler/crystal/syntax/parser.cr index ce3a1cc9b38d..4c41220d4234 100644 --- a/src/compiler/crystal/syntax/parser.cr +++ b/src/compiler/crystal/syntax/parser.cr @@ -1637,6 +1637,10 @@ module Crystal name = parse_path skip_space + unexpected_token unless @token.type.op_lt? || # Inheritance + @token.type.op_lparen? || # Generic Arguments + is_statement_end? + type_vars, splat_index = parse_type_vars superclass = nil @@ -1649,6 +1653,8 @@ module Crystal else superclass = parse_generic end + + unexpected_token unless @token.type.space? || is_statement_end? end skip_statement_end @@ -1668,6 +1674,10 @@ module Crystal class_def end + def is_statement_end? + @token.type.newline? || @token.type.op_semicolon? || @token.keyword?(:end) + end + def parse_type_vars type_vars = nil splat_index = nil