Skip to content

Commit

Permalink
Parser: Fix restrict grammar for name and supertype in type def (#12622)
Browse files Browse the repository at this point in the history
  • Loading branch information
caspiano committed Oct 23, 2022
1 parent e6de9e3 commit bd83c55
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
11 changes: 11 additions & 0 deletions spec/compiler/parser/parser_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
10 changes: 10 additions & 0 deletions src/compiler/crystal/syntax/parser.cr
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -1649,6 +1653,8 @@ module Crystal
else
superclass = parse_generic
end

unexpected_token unless @token.type.space? || is_statement_end?
end
skip_statement_end

Expand All @@ -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
Expand Down

0 comments on commit bd83c55

Please sign in to comment.