Skip to content

Commit

Permalink
Disallow assignments to calls with parentheses (#14527)
Browse files Browse the repository at this point in the history
  • Loading branch information
HertzDevil authored Apr 23, 2024
1 parent d31fe62 commit 2eed385
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 3 deletions.
9 changes: 9 additions & 0 deletions spec/compiler/parser/parser_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -267,6 +267,15 @@ module Crystal
assert_syntax_error "a.b(), c.d = 1"
assert_syntax_error "a.b, c.d() = 1"

assert_syntax_error "a() = 1"
assert_syntax_error "a {} = 1"
assert_syntax_error "a.b() = 1"
assert_syntax_error "a.[]() = 1"
assert_syntax_error "a() += 1"
assert_syntax_error "a {} += 1"
assert_syntax_error "a.b() += 1"
assert_syntax_error "a.[]() += 1"

it_parses "def foo\n1\nend", Def.new("foo", body: 1.int32)
it_parses "def downto(n)\n1\nend", Def.new("downto", ["n".arg], 1.int32)
it_parses "def foo ; 1 ; end", Def.new("foo", body: 1.int32)
Expand Down
6 changes: 3 additions & 3 deletions src/compiler/crystal/syntax/parser.cr
Original file line number Diff line number Diff line change
Expand Up @@ -376,6 +376,8 @@ module Crystal
break
when .op_eq?
slash_is_regex!
break unless can_be_assigned?(atomic)

if atomic.is_a?(Call) && atomic.name == "[]"
next_token_skip_space_or_newline

Expand All @@ -385,8 +387,6 @@ module Crystal
atomic.args << arg
atomic.end_location = arg.end_location
else
break unless can_be_assigned?(atomic)

if atomic.is_a?(Path) && (inside_def? || inside_fun? || @is_constant_assignment)
raise "dynamic constant assignment. Constants can only be declared at the top level or inside other types."
end
Expand Down Expand Up @@ -6185,7 +6185,7 @@ module Crystal
when Var, InstanceVar, ClassVar, Path, Global, Underscore
true
when Call
(node.obj.nil? && node.args.size == 0 && node.block.nil?) || node.name == "[]"
!node.has_parentheses? && ((node.obj.nil? && node.args.empty? && node.block.nil?) || node.name == "[]")
else
false
end
Expand Down

0 comments on commit 2eed385

Please sign in to comment.