diff --git a/const_opassign_test.go b/const_opassign_test.go new file mode 100644 index 0000000..dd50996 --- /dev/null +++ b/const_opassign_test.go @@ -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]) + } +} diff --git a/lexer/lexer.go b/lexer/lexer.go index 4a848e6..1539221 100644 --- a/lexer/lexer.go +++ b/lexer/lexer.go @@ -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, "**") } diff --git a/parser.go b/parser.go index eb9beb3..99fb211 100644 --- a/parser.go +++ b/parser.go @@ -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 { @@ -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 { @@ -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,