diff --git a/ast/ast.go b/ast/ast.go index ec72b53..355c611 100644 --- a/ast/ast.go +++ b/ast/ast.go @@ -241,6 +241,15 @@ type ModuleDef struct { Body []Node } +// SingletonClassDef opens the singleton (metaclass) of Target: `class << Target; +// Body; end`. Methods and constants defined in Body attach to Target's singleton +// class. `class << self` (Target is *SelfLit) is the idiomatic form for defining +// class methods; `class << obj` opens an arbitrary object's singleton class. +type SingletonClassDef struct { + Target Node + Body []Node +} + // Super calls the same-named method in the ancestor chain. Forward is true for a // bare `super` (passes the enclosing method's own arguments); otherwise Args are // the explicit arguments of `super(...)`. @@ -407,55 +416,56 @@ type RescueClause struct { Body []Node } -func (*Program) node() {} -func (*ScopedConst) node() {} -func (*IntLit) node() {} -func (*BignumLit) node() {} -func (*FloatLit) node() {} -func (*StringLit) node() {} -func (*SymbolLit) node() {} -func (*RegexpLit) node() {} -func (*XStr) node() {} -func (*ArrayLit) node() {} -func (*HashLit) node() {} -func (*RangeLit) node() {} -func (*BoolLit) node() {} -func (*NilLit) node() {} -func (*SelfLit) node() {} -func (*VarRef) node() {} -func (*Assign) node() {} -func (*BinaryExpr) node() {} -func (*UnaryExpr) node() {} -func (*Call) node() {} -func (*If) node() {} -func (*While) node() {} -func (*MethodDef) node() {} -func (*Return) node() {} -func (*ConstRef) node() {} -func (*ConstAssign) node() {} -func (*GVarRef) node() {} -func (*GVarAssign) node() {} -func (*CVarRef) node() {} -func (*CVarAssign) node() {} -func (*MultiAssign) node() {} -func (*MatchPattern) node() {} -func (*IvarRef) node() {} -func (*IvarAssign) node() {} -func (*ClassDef) node() {} -func (*ModuleDef) node() {} -func (*Super) node() {} -func (*Yield) node() {} -func (*Break) node() {} -func (*Next) node() {} -func (*OpAssign) node() {} -func (*Begin) node() {} -func (*StrInterp) node() {} -func (*Case) node() {} -func (*Retry) node() {} -func (*SplatArg) node() {} -func (*BlockPass) node() {} -func (*ForwardArgs) node() {} -func (*CaseIn) node() {} +func (*Program) node() {} +func (*ScopedConst) node() {} +func (*IntLit) node() {} +func (*BignumLit) node() {} +func (*FloatLit) node() {} +func (*StringLit) node() {} +func (*SymbolLit) node() {} +func (*RegexpLit) node() {} +func (*XStr) node() {} +func (*ArrayLit) node() {} +func (*HashLit) node() {} +func (*RangeLit) node() {} +func (*BoolLit) node() {} +func (*NilLit) node() {} +func (*SelfLit) node() {} +func (*VarRef) node() {} +func (*Assign) node() {} +func (*BinaryExpr) node() {} +func (*UnaryExpr) node() {} +func (*Call) node() {} +func (*If) node() {} +func (*While) node() {} +func (*MethodDef) node() {} +func (*Return) node() {} +func (*ConstRef) node() {} +func (*ConstAssign) node() {} +func (*GVarRef) node() {} +func (*GVarAssign) node() {} +func (*CVarRef) node() {} +func (*CVarAssign) node() {} +func (*MultiAssign) node() {} +func (*MatchPattern) node() {} +func (*IvarRef) node() {} +func (*IvarAssign) node() {} +func (*ClassDef) node() {} +func (*SingletonClassDef) node() {} +func (*ModuleDef) node() {} +func (*Super) node() {} +func (*Yield) node() {} +func (*Break) node() {} +func (*Next) node() {} +func (*OpAssign) node() {} +func (*Begin) node() {} +func (*StrInterp) node() {} +func (*Case) node() {} +func (*Retry) node() {} +func (*SplatArg) node() {} +func (*BlockPass) node() {} +func (*ForwardArgs) node() {} +func (*CaseIn) node() {} func (*ValuePattern) pattern() {} func (*BindPattern) pattern() {} diff --git a/command_args_test.go b/command_args_test.go new file mode 100644 index 0000000..0894d47 --- /dev/null +++ b/command_args_test.go @@ -0,0 +1,199 @@ +package parser_test + +import ( + "testing" + + "github.com/go-ruby-parser/parser" + "github.com/go-ruby-parser/parser/ast" +) + +// TestCommandCallKeywordArgs covers paren-less command calls whose arguments +// include `label: value` keyword pairs, which collapse into a trailing implicit +// Hash — the dominant Rails/DSL form (`render json: x, status: :ok`). +func TestCommandCallKeywordArgs(t *testing.T) { + cases := []struct { + src string + name string + wantPos int // positional args before the trailing hash + wantHashKeys int // keys in the trailing hash (0 ⇒ no trailing hash) + }{ + {"delegate :a, :b, to: :c", "delegate", 2, 1}, + {"validates :x, presence: true", "validates", 1, 1}, + {"render json: x, status: :ok", "render", 0, 2}, + {"foo a, b: 1, c: 2", "foo", 1, 2}, + {"belongs_to :user, optional: true", "belongs_to", 1, 1}, + } + for _, c := range cases { + call := topCall(t, c.src) + if call.Name != c.name { + t.Errorf("Parse(%q): Name=%q, want %q", c.src, call.Name, c.name) + } + total := c.wantPos + if c.wantHashKeys > 0 { + total++ + } + if len(call.Args) != total { + t.Fatalf("Parse(%q): %d args, want %d", c.src, len(call.Args), total) + } + if c.wantHashKeys > 0 { + h, ok := call.Args[len(call.Args)-1].(*ast.HashLit) + if !ok { + t.Fatalf("Parse(%q): last arg is %T, want *ast.HashLit", c.src, call.Args[len(call.Args)-1]) + } + if len(h.Keys) != c.wantHashKeys { + t.Errorf("Parse(%q): trailing hash has %d keys, want %d", c.src, len(h.Keys), c.wantHashKeys) + } + } + } +} + +// TestCommandCallMultiplePositional covers several bare positional arguments +// (`foo a, b, c`, `puts x, y`). +func TestCommandCallMultiplePositional(t *testing.T) { + cases := []struct { + src string + name string + wantArgs int + }{ + {"foo a, b, c", "foo", 3}, + {"puts x, y", "puts", 2}, + {"p 1, 2, 3, 4", "p", 4}, + } + for _, c := range cases { + call := topCall(t, c.src) + if call.Name != c.name || len(call.Args) != c.wantArgs { + t.Errorf("Parse(%q): %+v (want %s/%d args)", c.src, call, c.name, c.wantArgs) + } + } +} + +// TestCommandCallSplatStarters covers the splat / double-splat / block-pass +// argument starters in command position, plus a hugging unary sign. +func TestCommandCallSplatStarters(t *testing.T) { + // foo *args → single SplatArg. + if call := topCall(t, "foo *args"); len(call.Args) != 1 { + t.Fatalf("foo *args: %+v", call) + } else if _, ok := call.Args[0].(*ast.SplatArg); !ok { + t.Fatalf("foo *args: arg0 is %T, want *ast.SplatArg", call.Args[0]) + } + // foo **opts → trailing hash with a nil-key (double-splat) entry. + if call := topCall(t, "foo **opts"); len(call.Args) != 1 { + t.Fatalf("foo **opts: %+v", call) + } else if h, ok := call.Args[0].(*ast.HashLit); !ok || len(h.Keys) != 1 || h.Keys[0] != nil { + t.Fatalf("foo **opts: arg0 = %+v, want double-splat hash", call.Args[0]) + } + // foo &blk → BlockPass. + if call := topCall(t, "foo &blk"); len(call.Args) != 1 { + t.Fatalf("foo &blk: %+v", call) + } else if _, ok := call.Args[0].(*ast.BlockPass); !ok { + t.Fatalf("foo &blk: arg0 is %T, want *ast.BlockPass", call.Args[0]) + } + // foo a, *rest, k: 1 → positional, splat, then trailing hash. + call := topCall(t, "foo a, *rest, k: 1") + if len(call.Args) != 3 { + t.Fatalf("foo a, *rest, k: 1: %d args, want 3", len(call.Args)) + } + if _, ok := call.Args[1].(*ast.SplatArg); !ok { + t.Errorf("foo a, *rest, k: 1: arg1 is %T, want *ast.SplatArg", call.Args[1]) + } + if _, ok := call.Args[2].(*ast.HashLit); !ok { + t.Errorf("foo a, *rest, k: 1: arg2 is %T, want *ast.HashLit", call.Args[2]) + } +} + +// TestCommandCallMixedLambdaArg covers a lambda among the positional arguments +// and a trailing keyword (`has_many :posts, -> { ... }, dependent: :destroy`). +func TestCommandCallMixedLambdaArg(t *testing.T) { + call := topCall(t, "has_many :posts, -> { order(:id) }, dependent: :destroy") + if call.Name != "has_many" || len(call.Args) != 3 { + t.Fatalf("has_many: %+v (want 3 args)", call) + } + // arg1 is the lambda, modelled as a call to `lambda` carrying a block. + lam, ok := call.Args[1].(*ast.Call) + if !ok || lam.Block == nil { + t.Errorf("has_many arg1 = %T (%+v), want a lambda call with a block", call.Args[1], call.Args[1]) + } + if _, ok := call.Args[2].(*ast.HashLit); !ok { + t.Errorf("has_many arg2 is %T, want *ast.HashLit", call.Args[2]) + } +} + +// TestCommandCallRHS covers a command call as the right-hand side of an +// assignment: `x = foo a, b` parses as x = foo(a, b). +func TestCommandCallRHS(t *testing.T) { + prog, err := parser.Parse("x = foo a, b") + if err != nil { + t.Fatalf("Parse: %v", err) + } + asn, ok := prog.Body[0].(*ast.Assign) + if !ok || asn.Name != "x" { + t.Fatalf("top is %T, want Assign x", prog.Body[0]) + } + call, ok := asn.Value.(*ast.Call) + if !ok || call.Name != "foo" || len(call.Args) != 2 { + t.Fatalf("RHS = %+v, want call foo with 2 args", asn.Value) + } +} + +// TestCommandCallBlockBinding covers the `do…end` vs `{…}` precedence: a +// trailing `do…end` binds to the command call, while a braced block binds to the +// nearest call (the last argument). +func TestCommandCallBlockBinding(t *testing.T) { + // foo bar do end → block on foo, not bar. + outer := topCall(t, "foo bar do end") + if outer.Name != "foo" || outer.Block == nil { + t.Fatalf("foo bar do end: outer = %+v (want foo with a block)", outer) + } + if arg, ok := outer.Args[0].(*ast.Call); !ok || arg.Block != nil { + t.Errorf("foo bar do end: arg block should be nil, got %+v", outer.Args[0]) + } + + // foo a, b do |x| end → block on foo. + multi := topCall(t, "foo a, b do |x| end") + if multi.Name != "foo" || multi.Block == nil || len(multi.Args) != 2 { + t.Fatalf("foo a, b do |x| end: %+v", multi) + } + + // foo bar { |x| x } → braced block on the nearest call (bar). + brace := topCall(t, "foo bar { |x| x }") + if brace.Name != "foo" || brace.Block != nil { + t.Fatalf("foo bar { }: outer = %+v (want foo with no block)", brace) + } + if arg, ok := brace.Args[0].(*ast.Call); !ok || arg.Block == nil { + t.Errorf("foo bar { }: arg should carry the brace block, got %+v", brace.Args[0]) + } +} + +// TestCommandCallKeywordRegression guards that `key: value` outside a call still +// behaves (a bare label at statement start is not a valid statement) and that +// operator forms are not mis-read as command splats. +func TestCommandCallKeywordRegression(t *testing.T) { + // `foo * 2` (spaces both sides) is multiplication of the bare call result. + prog, err := parser.Parse("foo * 2") + if err != nil { + t.Fatalf("Parse(foo * 2): %v", err) + } + if _, ok := prog.Body[0].(*ast.BinaryExpr); !ok { + t.Errorf("foo * 2: top is %T, want *ast.BinaryExpr", prog.Body[0]) + } + // `foo - 2` (spaces both sides) is subtraction, not a command arg. + prog, err = parser.Parse("foo - 2") + if err != nil { + t.Fatalf("Parse(foo - 2): %v", err) + } + if _, ok := prog.Body[0].(*ast.BinaryExpr); !ok { + t.Errorf("foo - 2: top is %T, want *ast.BinaryExpr", prog.Body[0]) + } +} + +// TestCommandCallReceiverKeyword covers keyword args on a receiver command call +// (`obj.foo bar, baz: 1`). +func TestCommandCallReceiverKeyword(t *testing.T) { + call := topCall(t, "obj.foo bar, baz: 1") + if call.Name != "foo" || call.Recv == nil || len(call.Args) != 2 { + t.Fatalf("obj.foo bar, baz: 1: %+v", call) + } + if _, ok := call.Args[1].(*ast.HashLit); !ok { + t.Errorf("obj.foo bar, baz: 1: arg1 is %T, want *ast.HashLit", call.Args[1]) + } +} diff --git a/negate_bignum_test.go b/negate_bignum_test.go new file mode 100644 index 0000000..eeac20e --- /dev/null +++ b/negate_bignum_test.go @@ -0,0 +1,70 @@ +package parser_test + +import ( + "math/big" + "testing" + + "github.com/go-ruby-parser/parser" + "github.com/go-ruby-parser/parser/ast" +) + +// TestNegativeBignumLiteral covers a negated integer literal that overflows +// int64: the magnitude lexes as a BignumLit, so negation must produce a negated +// BignumLit rather than panicking on a bad type assertion (the cause of the +// real-world TypeAssertionError crashes on Rails sources). +func TestNegativeBignumLiteral(t *testing.T) { + cases := []struct { + src string + want string // decimal string of the expected big value + }{ + {"-9999999999999999999999999999999", "-9999999999999999999999999999999"}, + {"-9223372036854775808", "-9223372036854775808"}, // int64 min: magnitude overflows + {"-10000000000000000000000", "-10000000000000000000000"}, + } + for _, c := range cases { + prog, err := parser.Parse(c.src) + if err != nil { + t.Fatalf("Parse(%q): %v", c.src, err) + } + bn, ok := prog.Body[0].(*ast.BignumLit) + if !ok { + t.Fatalf("Parse(%q): top is %T, want *ast.BignumLit", c.src, prog.Body[0]) + } + want, _ := new(big.Int).SetString(c.want, 10) + if bn.Val.Cmp(want) != 0 { + t.Errorf("Parse(%q): value = %s, want %s", c.src, bn.Val, want) + } + } +} + +// TestNegativeBignumPostfixAndAssign covers the negated-bignum node flowing +// through a postfix chain and an assignment RHS (the surrounding paths the +// negate helper feeds). +func TestNegativeBignumPostfixAndAssign(t *testing.T) { + // (-big).abs — the negated bignum carries its own postfix chain. + call, ok := mustParseSingle(t, "(-9999999999999999999999).abs").(*ast.Call) + if !ok || call.Name != "abs" { + t.Fatalf("(-big).abs: top is %T, want call abs", call) + } + // x = -big — negated bignum as an assignment value. + asn, ok := mustParseSingle(t, "x = -10000000000000000000000").(*ast.Assign) + if !ok { + t.Fatalf("x = -big: top is %T, want *ast.Assign", asn) + } + if _, ok := asn.Value.(*ast.BignumLit); !ok { + t.Errorf("x = -big: RHS is %T, want *ast.BignumLit", asn.Value) + } +} + +// mustParseSingle parses src and returns its single top-level node. +func mustParseSingle(t *testing.T, src string) ast.Node { + t.Helper() + prog, err := parser.Parse(src) + if err != nil { + t.Fatalf("Parse(%q): %v", src, err) + } + if len(prog.Body) != 1 { + t.Fatalf("Parse(%q): want 1 node, got %d", src, len(prog.Body)) + } + return prog.Body[0] +} diff --git a/parser.go b/parser.go index 789109e..5a08455 100644 --- a/parser.go +++ b/parser.go @@ -109,17 +109,32 @@ type Parser struct { noPipe bool } -// Parse lexes and parses src into a Program. +// parseHook, when non-nil, runs at the start of Parse. It exists only so a +// white-box test can inject a non-parseError panic and exercise the recover's +// internal-error path; it is nil in normal operation. +var parseHook func() + +// Parse lexes and parses src into a Program. It never panics: a malformed input +// yields a parse error, and any unexpected internal panic is also surfaced as a +// parse error rather than propagating to the caller. func Parse(src string) (prog *ast.Program, err error) { toks := lexer.New(src).Tokenize() p := &Parser{toks: toks, scopes: []*scope{newScope(true)}} defer func() { if r := recover(); r != nil { - // Unchecked: a non-parseError is an internal bug and re-panics as a - // conversion error rather than leaving an uncovered re-panic branch. - prog, err = nil, r.(parseError) + if pe, ok := r.(parseError); ok { + prog, err = nil, pe + return + } + // An internal bug (e.g. an unexpected type assertion or index) must not + // crash the caller: report it as a parse error so the parser's contract + // of never panicking holds for every input. + prog, err = nil, parseError{msg: fmt.Sprintf("internal parser error: %v", r)} } }() + if parseHook != nil { + parseHook() + } body := p.parseStatements(map[token.Type]bool{}) p.expect(token.EOF) return &ast.Program{Body: body}, nil @@ -376,10 +391,15 @@ func (p *Parser) parseConstPath() (name string, path ast.Node) { func (p *Parser) parseClass() ast.Node { p.expect(token.CLASS) - // `class << self` (singleton-class body) is out of this front-end's scope; a - // SHOVEL here is not a constant path. - if p.is(token.SHOVEL) { - p.fail("singleton class (class << ...) is not supported") + // `class << target` opens target's singleton (metaclass). A SHOVEL here is + // the singleton-class form, not a constant path. + if p.accept(token.SHOVEL) { + target := p.parseTernary() + p.pushScope() // the singleton-class body has its own local scope + body := p.parseStatements(bodyEnd) + p.popScope() + p.expect(token.END) + return &ast.SingletonClassDef{Target: target, Body: body} } name, path := p.parseConstPath() super := "" @@ -1296,11 +1316,18 @@ func (p *Parser) parseBinary(minBP int) ast.Node { } } -// negateLiteral returns the negation of a numeric literal node. It is only -// called with an *ast.IntLit or *ast.FloatLit (the two numeric primaries). +// negateLiteral returns the negation of a numeric literal node. The MINUS path +// in parseUnary reaches here only after parsePrimary consumed an INT or FLOAT +// token, which yields exactly one of these three kinds: a FLOAT is always a +// FloatLit, and an INT is an IntLit or — when it overflows int64, e.g. +// -9999999999999999999999999999999 — a BignumLit. (An INT with invalid digits +// fails inside parsePrimary and never returns here.) func negateLiteral(n ast.Node) ast.Node { - if il, ok := n.(*ast.IntLit); ok { - return &ast.IntLit{Value: -il.Value} + switch lit := n.(type) { + case *ast.IntLit: + return &ast.IntLit{Value: -lit.Value} + case *ast.BignumLit: + return &ast.BignumLit{Val: new(big.Int).Neg(lit.Val)} } fl := n.(*ast.FloatLit) return &ast.FloatLit{Value: -fl.Value} @@ -1853,22 +1880,44 @@ func (p *Parser) canStartCommandArg() bool { token.BEGIN, token.CASE: // Value-producing keywords: `p begin; 1; end`, `p case x; when 1; 2; end`. return true + case token.LABEL: + // Keyword/hash argument without parens: `render json: x`, `delegate to: :c`. + return true case token.SCOPE: // A leading `::Name` (top-level constant) as a command argument: `puts ::Foo`. // Only when the `::` hugs a following constant, not the postfix `a ::b` form. return p.peekTok().Type == token.CONST - case token.MINUS, token.PLUS: - // Unary-style argument: `foo -1` (operand hugs the sign), not `foo - 1`. + case token.MINUS, token.PLUS, token.STAR, token.POW, token.AMPER: + // A sign/splat/double-splat/block-pass operand that hugs the next token is a + // unary-style command argument: `foo -1`, `foo *args`, `foo **opts`, `foo &blk`. + // With a space on both sides it is a binary operator: `foo - 1`, `foo * 2`. return !p.peekTok().SpaceBefore } return false } +// parseCommandArgs parses a paren-less argument list (`foo a, b, key: v`). It +// reuses parseOneCallArg, so it accepts the same positional/splat/block-pass and +// keyword/hash-pair forms a parenthesized call does, collapsing trailing +// `key: value` / `expr => value` pairs into one implicit Hash argument. func (p *Parser) parseCommandArgs() []ast.Node { - args := []ast.Node{p.parseBinary(0)} + // A trailing `do…end` binds to the command call, not to an argument that is + // itself a call (`foo bar do…end` → the block is foo's). Suppress block + // attachment while parsing the arguments so the enclosing postfix chain picks + // the `do` up for the command call. A braced `{…}` block is unaffected: it + // binds tighter and always attaches to the nearest call. + saved := p.noDo + p.noDo = true + var args []ast.Node + var kw *ast.HashLit + p.parseOneCallArg(&args, &kw) for p.accept(token.COMMA) { p.skipNewlines() - args = append(args, p.parseBinary(0)) + p.parseOneCallArg(&args, &kw) + } + p.noDo = saved + if kw != nil { + args = append(args, kw) } return args } diff --git a/robustness_internal_test.go b/robustness_internal_test.go new file mode 100644 index 0000000..856c5a5 --- /dev/null +++ b/robustness_internal_test.go @@ -0,0 +1,34 @@ +package parser + +import ( + "strings" + "testing" +) + +// TestParseRecoversInternalPanic verifies the never-panic contract: an +// unexpected internal panic (not a parseError) is converted into a clean parse +// error instead of propagating to the caller. The parseHook seam injects such a +// panic; outside tests it is nil. +func TestParseRecoversInternalPanic(t *testing.T) { + defer func() { parseHook = nil }() + parseHook = func() { panic("boom") } + + prog, err := Parse("1 + 1") + if prog != nil { + t.Errorf("Parse: prog = %+v, want nil on internal panic", prog) + } + if err == nil { + t.Fatal("Parse: err is nil, want an internal parser error") + } + if !strings.Contains(err.Error(), "internal parser error") { + t.Errorf("Parse: err = %q, want it to mention an internal parser error", err.Error()) + } +} + +// TestParseRecoversParseError confirms the ordinary parse-error path still flows +// through the recover (a genuine syntax error remains a clean parseError). +func TestParseRecoversParseError(t *testing.T) { + if _, err := Parse("def "); err == nil { + t.Fatal("Parse(def ): want a parse error, got nil") + } +} diff --git a/scope_resolution_test.go b/scope_resolution_test.go index 1d203c0..636c603 100644 --- a/scope_resolution_test.go +++ b/scope_resolution_test.go @@ -167,8 +167,15 @@ func TestScopeResolutionPostfixStillWorks(t *testing.T) { } } -func TestScopeResolutionSingletonClassRejected(t *testing.T) { - if _, err := parser.Parse("class << self; end"); err == nil { - t.Fatal("class << self should be rejected (out of scope), got no error") +// TestScopeResolutionSingletonClassParsed confirms the singleton-class form +// `class << self` is now parsed (it was previously rejected). Full coverage of +// the node lives in singleton_class_test.go. +func TestScopeResolutionSingletonClassParsed(t *testing.T) { + prog, err := parser.Parse("class << self; end") + if err != nil { + t.Fatalf("class << self: %v", err) + } + if _, ok := prog.Body[0].(*ast.SingletonClassDef); !ok { + t.Fatalf("class << self: top is %T, want *ast.SingletonClassDef", prog.Body[0]) } } diff --git a/singleton_class_test.go b/singleton_class_test.go new file mode 100644 index 0000000..2ec5cf2 --- /dev/null +++ b/singleton_class_test.go @@ -0,0 +1,118 @@ +package parser_test + +import ( + "testing" + + "github.com/go-ruby-parser/parser" + "github.com/go-ruby-parser/parser/ast" +) + +// topSingleton parses src and returns the single top-level SingletonClassDef. +func topSingleton(t *testing.T, src string) *ast.SingletonClassDef { + t.Helper() + prog, err := parser.Parse(src) + if err != nil { + t.Fatalf("Parse(%q): %v", src, err) + } + if len(prog.Body) != 1 { + t.Fatalf("Parse(%q): want 1 top-level node, got %d", src, len(prog.Body)) + } + sc, ok := prog.Body[0].(*ast.SingletonClassDef) + if !ok { + t.Fatalf("Parse(%q): top node is %T, want *ast.SingletonClassDef", src, prog.Body[0]) + } + return sc +} + +// TestSingletonClassSelf covers `class << self` — the idiomatic class-method +// form. The target is *SelfLit and the body holds the defined methods. +func TestSingletonClassSelf(t *testing.T) { + sc := topSingleton(t, "class << self; def x; 1; end; end") + if _, ok := sc.Target.(*ast.SelfLit); !ok { + t.Fatalf("Target is %T, want *ast.SelfLit", sc.Target) + } + if len(sc.Body) != 1 { + t.Fatalf("Body has %d nodes, want 1", len(sc.Body)) + } + md, ok := sc.Body[0].(*ast.MethodDef) + if !ok || md.Name != "x" { + t.Fatalf("Body[0] = %T (%+v), want method def x", sc.Body[0], sc.Body[0]) + } +} + +// TestSingletonClassSelfNewlines covers the multi-line layout (no `;`). +func TestSingletonClassSelfNewlines(t *testing.T) { + sc := topSingleton(t, "class << self\n def x\n 1\n end\nend") + if _, ok := sc.Target.(*ast.SelfLit); !ok { + t.Fatalf("Target is %T, want *ast.SelfLit", sc.Target) + } + if len(sc.Body) != 1 { + t.Fatalf("Body has %d nodes, want 1", len(sc.Body)) + } +} + +// TestSingletonClassLocalTarget covers `class << obj` where obj is a local +// variable — the target resolves to a VarRef read. +func TestSingletonClassLocalTarget(t *testing.T) { + prog, err := parser.Parse("o = Object.new\nclass << o\n def y; 2; end\nend") + if err != nil { + t.Fatalf("Parse: %v", err) + } + if len(prog.Body) != 2 { + t.Fatalf("want 2 top-level nodes, got %d", len(prog.Body)) + } + sc, ok := prog.Body[1].(*ast.SingletonClassDef) + if !ok { + t.Fatalf("Body[1] is %T, want *ast.SingletonClassDef", prog.Body[1]) + } + vr, ok := sc.Target.(*ast.VarRef) + if !ok || vr.Name != "o" { + t.Fatalf("Target = %T (%+v), want VarRef o", sc.Target, sc.Target) + } +} + +// TestSingletonClassConstTarget covers `class << SomeConst` (e.g. a module's +// metaclass) — the target is a constant call/ref expression. +func TestSingletonClassConstTarget(t *testing.T) { + sc := topSingleton(t, "class << Foo\n def bar; end\nend") + if _, ok := sc.Target.(*ast.ConstRef); !ok { + t.Fatalf("Target is %T, want *ast.ConstRef", sc.Target) + } +} + +// TestSingletonClassExprTarget covers an arbitrary expression target such as a +// method-call result: `class << obj.thing`. +func TestSingletonClassExprTarget(t *testing.T) { + sc := topSingleton(t, "class << obj.thing\n def z; end\nend") + call, ok := sc.Target.(*ast.Call) + if !ok || call.Name != "thing" || call.Recv == nil { + t.Fatalf("Target = %T (%+v), want call to thing on a receiver", sc.Target, sc.Target) + } +} + +// TestSingletonClassEmptyBody covers a singleton class with no body statements. +func TestSingletonClassEmptyBody(t *testing.T) { + sc := topSingleton(t, "class << self\nend") + if len(sc.Body) != 0 { + t.Fatalf("Body has %d nodes, want 0", len(sc.Body)) + } +} + +// TestSingletonClassNested covers the common `class Foo; class << self; ...` +// nesting used to declare class methods inside a class body. +func TestSingletonClassNested(t *testing.T) { + prog, err := parser.Parse("class Foo\n class << self\n def bar; end\n end\nend") + if err != nil { + t.Fatalf("Parse: %v", err) + } + cd, ok := prog.Body[0].(*ast.ClassDef) + if !ok || cd.Name != "Foo" { + t.Fatalf("top is %T, want ClassDef Foo", prog.Body[0]) + } + if len(cd.Body) != 1 { + t.Fatalf("class body has %d nodes, want 1", len(cd.Body)) + } + if _, ok := cd.Body[0].(*ast.SingletonClassDef); !ok { + t.Fatalf("class body[0] is %T, want *ast.SingletonClassDef", cd.Body[0]) + } +}