Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
93 changes: 93 additions & 0 deletions const_opassign_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
package parser

import (
"testing"

"github.com/go-ruby-parser/parser/ast"
)

// TestConstOpAssign covers compound assignment to a constant (`C += 1`,
// `C ||= x`) and to a scope-resolved constant (`A::B += 1`, `A::B ||= x`), which
// the parser previously rejected. Arithmetic and `&&=` desugar to `C = C OP x`;
// `||=` is guarded behind `defined?` so it defines an undefined constant instead
// of raising, matching MRI 4.0.6.
func TestConstOpAssign(t *testing.T) {
for _, src := range []string{
`C += 1`, `C -= 1`, `C *= 2`, `C **= 2`, `C &&= 1`, `C ||= 1`,
`A::B += 1`, `A::B ||= 1`, `Foo::Bar::BAZ *= 3`,
`(x; ConstantSpecs)::OpAssign += 2`,
`defined?(A += 1)`,
} {
if _, err := Parse(src); err != nil {
t.Errorf("Parse(%q) error: %v", src, err)
}
}

// `C += 1` desugars to `C = C + 1` (a ConstAssign whose value adds a read).
prog, err := Parse(`C += 1`)
if err != nil {
t.Fatalf("Parse error: %v", err)
}
ca, ok := prog.Body[0].(*ast.ConstAssign)
if !ok {
t.Fatalf("C += 1: expected *ast.ConstAssign, got %T", prog.Body[0])
}
bin, ok := ca.Value.(*ast.BinaryExpr)
if !ok || bin.Op != "+" {
t.Fatalf("C += 1: expected value `C + 1`, got %#v", ca.Value)
}
if _, ok := bin.Left.(*ast.ConstRef); !ok {
t.Fatalf("C += 1: expected a ConstRef read on the left, got %T", bin.Left)
}

// `C ||= 1` desugars to `(defined?(C) && C) || (C = 1)` so an undefined
// constant is defined rather than read.
prog, err = Parse(`C ||= 1`)
if err != nil {
t.Fatalf("Parse error: %v", err)
}
or, ok := prog.Body[0].(*ast.BinaryExpr)
if !ok || or.Op != "||" {
t.Fatalf("C ||= 1: expected a top-level `||`, got %#v", prog.Body[0])
}
guard, ok := or.Left.(*ast.BinaryExpr)
if !ok || guard.Op != "&&" {
t.Fatalf("C ||= 1: expected a `defined?(C) && C` guard, got %#v", or.Left)
}
call, ok := guard.Left.(*ast.Call)
if !ok || call.Name != "defined?" {
t.Fatalf("C ||= 1: expected `defined?(C)` in the guard, got %#v", guard.Left)
}
if _, ok := or.Right.(*ast.ConstAssign); !ok {
t.Fatalf("C ||= 1: expected a ConstAssign on the right, got %T", or.Right)
}

// The scoped `||=` form is guarded the same way and targets a ScopedConst.
prog, err = Parse(`A::B ||= 1`)
if err != nil {
t.Fatalf("Parse error: %v", err)
}
or = prog.Body[0].(*ast.BinaryExpr)
if _, ok := or.Right.(*ast.ScopedConstAssign); !ok {
t.Fatalf("A::B ||= 1: expected a ScopedConstAssign on the right, got %T", or.Right)
}
}

// TestPowerAssign covers the `**=` power-assignment operator, which the lexer
// previously split into `**` and `=` (a parse error), for local, instance, and
// constant targets and right-associatively chained.
func TestPowerAssign(t *testing.T) {
for _, src := range []string{`x **= 2`, `@i **= 2`, `C **= 2`, `a **= b **= 2`} {
if _, err := Parse(src); err != nil {
t.Errorf("Parse(%q) error: %v", src, err)
}
}
// `**` and `**=` remain distinct: `x ** 2` is the power operator.
prog, err := Parse(`x ** 2`)
if err != nil {
t.Fatalf("Parse error: %v", err)
}
if bin, ok := prog.Body[0].(*ast.BinaryExpr); !ok || bin.Op != "**" {
t.Fatalf("x ** 2: expected a `**` BinaryExpr, got %#v", prog.Body[0])
}
}
5 changes: 5 additions & 0 deletions lexer/lexer.go
Original file line number Diff line number Diff line change
Expand Up @@ -322,6 +322,11 @@ func (l *Lexer) lexToken() token.Token {
case '*':
if l.peek() == '*' {
l.advance()
if l.peek() == '=' { // `**=` power-assignment
l.advance()
l.state = exprBegin
return mk(token.OPASSIGN, "**")
}
l.state = exprBegin
return mk(token.POW, "**")
}
Expand Down
32 changes: 32 additions & 0 deletions parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -1897,6 +1897,15 @@ func (p *Parser) parseExprOrAssign() ast.Node {
rhs := p.parseExprOrAssign()
return &ast.CVarAssign{Name: name, Value: &ast.BinaryExpr{Op: op, Left: &ast.CVarRef{Name: name}, Right: rhs}}
}
// Compound assignment to a constant: NAME OP= expr (`C += 1`, `C ||= default`).
if p.is(token.CONST) && p.peekTok().Type == token.OPASSIGN {
name := p.advance().Lit
op := p.advance().Lit
rhs := p.parseExprOrAssign()
return constOpAssign(op, &ast.ConstRef{Name: name}, rhs, func(v ast.Node) ast.Node {
return &ast.ConstAssign{Name: name, Value: v}
})
}
left := p.parseTernary()
if p.is(token.OPASSIGN) {
if call, ok := left.(*ast.Call); ok && call.Recv != nil {
Expand All @@ -1918,6 +1927,14 @@ func (p *Parser) parseExprOrAssign() ast.Node {
return &ast.Call{Recv: call.Recv, Name: call.Name + "=", Args: []ast.Node{newVal}}
}
}
// Compound scope-resolved constant assignment: `A::B OP= v`.
if sc, ok := left.(*ast.ScopedConst); ok {
op := p.advance().Lit
rhs := p.parseExprOrAssign()
return constOpAssign(op, sc, rhs, func(v ast.Node) ast.Node {
return &ast.ScopedConstAssign{Target: sc, Value: v}
})
}
}
if p.is(token.ASSIGN) {
if call, ok := left.(*ast.Call); ok && call.Recv != nil {
Expand Down Expand Up @@ -1947,6 +1964,21 @@ func (p *Parser) parseExprOrAssign() ast.Node {
return p.withRescueModifier(left)
}

// constOpAssign builds the desugaring of a constant compound assignment
// `TARGET OP= rhs`. ref is a fresh read of the target (a *ConstRef or a
// *ScopedConst) and assign wraps a value into the target's assignment node. For
// `||=` the read is guarded behind `defined?`, so `C ||= x` defines C when C is
// undefined rather than raising — matching MRI: `(defined?(C) && C) || (C = x)`.
// Every other operator (`+=`, `-=`, `&&=`, …) reads the constant directly, as
// MRI does (raising NameError on an undefined constant).
func constOpAssign(op string, ref, rhs ast.Node, assign func(ast.Node) ast.Node) ast.Node {
if op == "||" {
guard := &ast.BinaryExpr{Op: "&&", Left: &ast.Call{Name: "defined?", Args: []ast.Node{ref}}, Right: ref}
return &ast.BinaryExpr{Op: "||", Left: guard, Right: assign(rhs)}
}
return assign(&ast.BinaryExpr{Op: op, Left: ref, Right: rhs})
}

// parseAssignRhs parses the right-hand side of a single-target assignment. It is
// usually one expression (chainable: `a = b = 1`), but a top-level comma — or a
// leading `*splat` — makes the RHS an implicit array: `x = 1, 2, 3` ≡ `x = [1,
Expand Down