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 = ...anddef 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 for2+
# a single-expression method body. Prism flattens this to the same3+
# DefNode shape as a regular def with a one-statement StatementsNode4+
# body, so the existing codegen path supports it transparently. This5+
# test pins that contract — if a future Prism upgrade emits a distinct6+
# node type (e.g. SingleLineMethodDefinitionNode), the test breaks7+
# loudly instead of silently regressing.8+
9+
# 1. Plain integer return.10+
def double(x) = x * 211+
puts double(21)12+
# 4213+
14+
# 2. String return with interpolation.15+
def greet(name) = "hello, #{name}"16+
puts greet("world")17+
# hello, world18+
19+
# 3. Self-recursive endless method (still expressible, since the body20+
# is one expression).21+
def fact(n) = n <= 1 ? 1 : n * fact(n - 1)22+
puts fact(5)23+
# 12024+
25+
# 4. No-arg endless method.26+
def answer = 4227+
puts answer28+
# 4229+
30+
# 5. Endless method using a block-passing call.31+
def doubled_max(arr) = arr.map { |x| x * 2 }.max32+
puts doubled_max([1, 4, 2])33+
# 834+
35+
# 6. Class endless method (instance + class methods).36+
class Box37+
def self.unit = 138+
def initialize(v); @v = v; end39+
def double = @v * 240+
def name = "Box"41+
end42+
43+
puts Box.unit44+
# 145+
puts Box.new(7).double46+
# 1447+
puts Box.new(0).name48+
# Box49+
50+
# 7. Boolean-returning endless method.51+
def positive?(n) = n > 052+
puts positive?(10)53+
# true54+
puts positive?(-1)55+
# false56+
57+
# 8. Method composition (one endless method calling another).58+
def square(x) = x * x59+
def square_of_sum(a, b) = square(a + b)60+
puts square_of_sum(2, 3)61+
# 25