Commit c65db5b5

c65db5b505dbMerged

Ryan Seys <[email protected]> · 6 months ago · 1 file · +1 added

Description

test(codegen): pin endless method support (def foo(x) = expr)

Endless methods (Ruby 3.0+) already work — Prism normalizes def foo(x) = expr into the same DefNode shape as a regular def with a one-statement StatementsNode body, so the existing codegen needs no change. This test pins the contract:

  • plain integer return
  • string return with concatenation
  • self-recursive endless method (n <= 1 ? 1 : n * fact(n - 1))
  • no-arg form (def answer = 42)
  • block-passing call inside the body (def doubled_max(arr) = arr.map { |x| x * 2 }.max)
  • class endless methods (both def self.X = ... and def X = ...)

If a future Prism upgrade emits a distinct node type (e.g. SingleLineMethodDefinitionNode), this test breaks loudly instead of silently regressing. The README's "Supported Ruby Features" section will be updated in a later commit to reflect the support.

Tests: 189 pass.

Details

Commit
c65db5b505db
Parent
02005f26deba

test/endless_method.rbaddedView file

1+# Endless methods (Ruby 3.0+): `def name(args) = expr` is shorthand for
2+# a single-expression method body. Prism flattens this to the same
3+# DefNode shape as a regular def with a one-statement StatementsNode
4+# body, so the existing codegen path supports it transparently. This
5+# test pins that contract — if a future Prism upgrade emits a distinct
6+# node type (e.g. SingleLineMethodDefinitionNode), the test breaks
7+# loudly instead of silently regressing.
8+
9+# 1. Plain integer return.
10+def double(x) = x * 2
11+puts double(21)
12+# 42
13+
14+# 2. String return with interpolation.
15+def greet(name) = "hello, #{name}"
16+puts greet("world")
17+# hello, world
18+
19+# 3. Self-recursive endless method (still expressible, since the body
20+# is one expression).
21+def fact(n) = n <= 1 ? 1 : n * fact(n - 1)
22+puts fact(5)
23+# 120
24+
25+# 4. No-arg endless method.
26+def answer = 42
27+puts answer
28+# 42
29+
30+# 5. Endless method using a block-passing call.
31+def doubled_max(arr) = arr.map { |x| x * 2 }.max
32+puts doubled_max([1, 4, 2])
33+# 8
34+
35+# 6. Class endless method (instance + class methods).
36+class Box
37+ def self.unit = 1
38+ def initialize(v); @v = v; end
39+ def double = @v * 2
40+ def name = "Box"
41+end
42+
43+puts Box.unit
44+# 1
45+puts Box.new(7).double
46+# 14
47+puts Box.new(0).name
48+# Box
49+
50+# 7. Boolean-returning endless method.
51+def positive?(n) = n > 0
52+puts positive?(10)
53+# true
54+puts positive?(-1)
55+# false
56+
57+# 8. Method composition (one endless method calling another).
58+def square(x) = x * x
59+def square_of_sum(a, b) = square(a + b)
60+puts square_of_sum(2, 3)
61+# 25