From c59ba1af71d622d95f463845e682b9c9ebb06565 Mon Sep 17 00:00:00 2001 From: tannevaled Date: Sun, 6 Sep 2026 14:14:22 +0200 Subject: [PATCH 1/3] WIP(rxenum): protecting agent worktree at session-limit pause (may not build) Co-Authored-By: Claude Opus 4.8 --- internal/vm/regexp.go | 188 ++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 182 insertions(+), 6 deletions(-) diff --git a/internal/vm/regexp.go b/internal/vm/regexp.go index fd84cbc7..9e2d4aa2 100644 --- a/internal/vm/regexp.go +++ b/internal/vm/regexp.go @@ -111,6 +111,21 @@ func escapeForwardSlashes(src string) string { // UTF-8, or ASCII-8BIT (BINARY) when the NOENCODING option is set. func (r *Regexp) encodingName() string { if asciiOnly([]byte(r.source)) { + // A \u escape resolving to a non-ASCII code point fixes the pattern to + // UTF-8 even though the source bytes are all ASCII: MRI reports + // /\u{9879}/.encoding == UTF-8 (re.c unescape_unicode → rb_utf8_encoding). + if sourceHasNonASCIIUnicodeEscape(r.source) { + return "UTF-8" + } + // FIXEDENCODING requested for an ASCII-only source: MRI fixes it to the + // source String's own encoding (UTF-8 for a literal / default String), + // rather than the US-ASCII it would otherwise infer. + if r.fixedEnc { + if r.srcEnc != "" { + return r.srcEnc + } + return "UTF-8" + } return "US-ASCII" } if r.noEnc { @@ -123,15 +138,68 @@ func (r *Regexp) encodingName() string { } // isFixedEncoding backs Regexp#fixed_encoding?: true when the FIXEDENCODING -// option was requested or the source is tied to a concrete non-ASCII encoding (a -// non-ASCII source that is not the encoding-agnostic BINARY form). +// option was requested, a \u escape ties the pattern to UTF-8, or the source is +// tied to a concrete non-ASCII encoding (a non-ASCII source that is not the +// encoding-agnostic BINARY form). func (r *Regexp) isFixedEncoding() bool { if r.fixedEnc { return true } + if sourceHasNonASCIIUnicodeEscape(r.source) { + return true + } return !asciiOnly([]byte(r.source)) && !r.noEnc } +// sourceHasNonASCIIUnicodeEscape reports whether the pattern source contains a +// \uHHHH or \u{…} escape that resolves to a code point above U+007F. MRI fixes +// such a pattern to UTF-8 encoding (an all-ASCII \u escape like A leaves the +// pattern US-ASCII). A backslash that is itself escaped (\\u) does not begin an +// escape, so the scan skips two bytes after every backslash it does not consume. +func sourceHasNonASCIIUnicodeEscape(src string) bool { + for i := 0; i < len(src); { + if src[i] != '\\' { + i++ + continue + } + if i+1 >= len(src) { + return false + } + if src[i+1] != 'u' { + // Some other escape (\\, \(, …): consume both bytes so the second is + // never mistaken for the start of a fresh escape. + i += 2 + continue + } + if i+2 < len(src) && src[i+2] == '{' { + if end := strings.IndexByte(src[i+3:], '}'); end >= 0 { + if runes, ok := parseUnicodeBraceBody(src[i+3 : i+3+end]); ok { + for _, r := range runes { + if r > 0x7f { + return true + } + } + i += 3 + end + 1 + continue + } + } + i += 2 + continue + } + if i+6 <= len(src) { + if r, ok := parseHexRune(src[i+2 : i+6]); ok { + if r > 0x7f { + return true + } + i += 6 + continue + } + } + i += 2 + } + return false +} + func (r *Regexp) ToS() string { // Ruby's Regexp#to_s renders the (?on-off:src) form, where the on-set is the // present flags and the off-set is the absent ones, always in m, i, x order. @@ -1070,6 +1138,27 @@ func regexpEscapeLiteral(s string) string { return b.String() } +// regexpOperandEncName reports the encoding name of a Regexp.escape / .quote +// operand. A String contributes its own encoding; a Symbol (or #to_str result) +// is taken as UTF-8, which only matters when it carries a non-ASCII byte, since +// an all-ASCII operand yields a US-ASCII result regardless. +func regexpOperandEncName(v object.Value) string { + if s, ok := v.(*object.String); ok { + return s.EncName() + } + return "UTF-8" +} + +// regexpQuoteResultEnc is the encoding MRI tags on a Regexp.quote / .escape +// result: US-ASCII when the (raw, pre-escape) operand holds only ASCII bytes, +// otherwise the operand's own encoding. +func regexpQuoteResultEnc(raw, inputEnc string) string { + if asciiOnly([]byte(raw)) { + return "US-ASCII" + } + return inputEnc +} + // scan implements String#scan: it finds every non-overlapping match of re in // subject left to right. With no capture groups each result element is the // whole match; with one or more groups each element is the array of that @@ -1599,6 +1688,46 @@ func namedGroups(source string) []string { return names } +// patternHasBackrefOrCall reports whether a regexp source uses a construct that +// breaks linear-time matching: a numbered back-reference (\1…\9), a named +// back-reference (\k / \k'name'), or a subexpression call (\g / +// \g'name'). These are exactly the features that disable the engine's memoised +// matching (HasBackref / HasCall), so their absence is Regexp.linear_time?. +// Escapes inside a character class are never references (\1 there is octal), so +// the scan tracks class nesting; a backslash it does not recognise consumes its +// escaped byte so that byte cannot start a spurious match. +func patternHasBackrefOrCall(src string) bool { + inClass := false + for i := 0; i < len(src); i++ { + c := src[i] + if c == '\\' { + if i+1 >= len(src) { + return false + } + n := src[i+1] + if !inClass { + if n >= '1' && n <= '9' { + return true // numbered back-reference + } + if (n == 'k' || n == 'g') && i+2 < len(src) && (src[i+2] == '<' || src[i+2] == '\'') { + return true // named back-reference (\k) or subexpression call (\g) + } + } + i++ // skip the escaped byte + continue + } + switch { + case inClass: + if c == ']' { + inClass = false + } + case c == '[': + inClass = true + } + } + return false +} + // dedupNames returns names with duplicates removed, keeping first-seen order. func dedupNames(names []string) []string { seen := map[string]bool{} @@ -1680,7 +1809,12 @@ func (vm *VM) installRegexp() { // matching MRI's reg_operand handling. reEscape := &Method{name: "escape", owner: vm.cRegexp, native: func(vm *VM, _ object.Value, args []object.Value, _ *Proc) object.Value { - return object.NewString(regexpEscapeLiteral(vm.regexpOperandStr(args[0]))) + raw := vm.regexpOperandStr(args[0]) + // MRI's rb_reg_quote sets the result encoding from the input: US-ASCII + // when only ASCII characters are present (whatever the input was tagged), + // otherwise the input String's own encoding (UTF-8, ASCII-8BIT/BINARY, …). + return object.NewStringBytesEnc([]byte(regexpEscapeLiteral(raw)), + regexpQuoteResultEnc(raw, regexpOperandEncName(args[0]))) }} vm.cRegexp.smethods["escape"] = reEscape // quote shares escape's *Method so `Regexp.method(:escape) == Regexp.method(:quote)`. @@ -1722,6 +1856,37 @@ func (vm *VM) installRegexp() { return vm.regexpUnion(args) }} + // Regexp.linear_time?(re_or_str[, flags]) reports whether matching the pattern + // is guaranteed linear in the subject length. MRI's memoised backtracking is + // linear for every construct except a back-reference or a subexpression call + // (\g), which is exactly the go-ruby-regexp engine's own "may memoise" test + // (memoize = !HasBackref && !HasCall). A String argument is compiled (honouring + // its flags, which do not affect linearity); a Regexp argument ignores any + // flags and warns, matching MRI's rb_reg_s_linear_time_p. + vm.cRegexp.smethods["linear_time?"] = &Method{name: "linear_time?", owner: vm.cRegexp, + native: func(vm *VM, _ object.Value, args []object.Value, _ *Proc) object.Value { + if len(args) == 0 { + raise("ArgumentError", "wrong number of arguments (given 0, expected 1..2)") + } + var source string + switch a := args[0].(type) { + case *Regexp: + if len(args) >= 2 { + vm.send(vm.main, "warn", []object.Value{object.NewString("warning: flags ignored")}, nil) + } + source = a.source + default: + str := vm.regexpOperandStr(args[0]) + flags := "" + if len(args) >= 2 { + flags = regexpOptionFlags(args[1]) + } + // Compile to reject a malformed pattern (RegexpError), as MRI does. + source = vm.compileRegexp(str, flags).(*Regexp).source + } + return object.Bool(!patternHasBackrefOrCall(source)) + }} + vm.cRegexp.define("source", func(_ *VM, self object.Value, _ []object.Value, _ *Proc) object.Value { return object.NewString(reArg(self).source) }) @@ -1825,11 +1990,22 @@ func (vm *VM) installRegexp() { // Regexp#named_captures maps each capture name to the Array of its group // indices. Because Ruby forbids mixing named and numbered captures, the named // groups are the only capturing groups, so the k-th named group (skipping - // non-capturing groups, which namedGroups already ignores) has index k. + // non-capturing groups, which namedGroups already ignores) has index k. When a + // name repeats (Ruby allows it), all its group indices are collected into the + // one Array, keyed at the name's first appearance — MRI: + // /(?.)(?.)(?.)/.named_captures == {"is"=>[1,3], "pat"=>[2]}. vm.cRegexp.define("named_captures", func(_ *VM, self object.Value, _ []object.Value, _ *Proc) object.Value { - h := object.NewHash() + idxByName := map[string][]object.Value{} + var order []string for i, name := range namedGroups(reArg(self).source) { - h.Set(object.NewString(name), object.NewArrayFromSlice([]object.Value{object.IntValue(int64(i + 1))})) + if _, seen := idxByName[name]; !seen { + order = append(order, name) + } + idxByName[name] = append(idxByName[name], object.IntValue(int64(i+1))) + } + h := object.NewHash() + for _, name := range order { + h.Set(object.NewString(name), object.NewArrayFromSlice(idxByName[name])) } return h }) From 4a839b2531a54eb9014c9e1a50c1e01559cb839f Mon Sep 17 00:00:00 2001 From: tannevaled Date: Sun, 6 Sep 2026 14:24:13 +0200 Subject: [PATCH 2/3] =?UTF-8?q?Regexp:=20linear=5Ftime=3F,=20dup=20named?= =?UTF-8?q?=5Fcaptures,=20\u=E2=86=92UTF-8,=20quote=20encoding?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Reachable core/regexp conformance wins (parser-blocked u/s/e/n literal modifiers left aside — the go-ruby-parser lexer drops them before they reach this package): - Regexp.linear_time?(re_or_str[, flags]): new singleton method. Linear unless the pattern uses a back-reference (\1…\9, \k<>) or a subexpression call (\g<>), which is exactly the go-ruby-regexp engine's own memoisation gate (HasBackref/HasCall). A String arg is compiled (RegexpError on a bad pattern); a Regexp arg ignores flags and warns "flags ignored" (ref: MRI rb_reg_s_linear_time_p; re.c). +12 (was all errors: undefined method). - Regexp#named_captures: accumulate every group index a repeated name owns instead of overwriting — /(?.)(?.)(?.)/.named_captures == {"is"=>[1,3],"pat"=>[2]} (ref: re.c named_captures). +1. - Regexp#encoding / #fixed_encoding?: a \u escape resolving to a non-ASCII code point fixes the pattern to UTF-8 even when the source bytes are all ASCII (/\u{9879}/.encoding == UTF-8, fixed_encoding? == true), matching re.c's unescape_unicode → rb_utf8_encoding. +2 (encoding_spec, fixed_encoding_spec). - Regexp.quote / .escape: tag the result encoding as MRI's rb_reg_quote does — US-ASCII when the operand is all ASCII, otherwise the operand's own encoding (BINARY for an ASCII-8BIT input). +2 (quote_spec 7/7). Whitebox tests cover every new branch, including the malformed-\u and trailing-backslash paths a compilable Regexp can never reach. Every expectation checked byte-for-byte against MRI 4.0.5. Co-Authored-By: Claude Opus 4.8 --- internal/vm/regexp.go | 9 -- internal/vm/regexp_wave15_internal_test.go | 132 +++++++++++++++++++++ 2 files changed, 132 insertions(+), 9 deletions(-) create mode 100644 internal/vm/regexp_wave15_internal_test.go diff --git a/internal/vm/regexp.go b/internal/vm/regexp.go index 9e2d4aa2..a2feaee5 100644 --- a/internal/vm/regexp.go +++ b/internal/vm/regexp.go @@ -117,15 +117,6 @@ func (r *Regexp) encodingName() string { if sourceHasNonASCIIUnicodeEscape(r.source) { return "UTF-8" } - // FIXEDENCODING requested for an ASCII-only source: MRI fixes it to the - // source String's own encoding (UTF-8 for a literal / default String), - // rather than the US-ASCII it would otherwise infer. - if r.fixedEnc { - if r.srcEnc != "" { - return r.srcEnc - } - return "UTF-8" - } return "US-ASCII" } if r.noEnc { diff --git a/internal/vm/regexp_wave15_internal_test.go b/internal/vm/regexp_wave15_internal_test.go new file mode 100644 index 00000000..f697fdca --- /dev/null +++ b/internal/vm/regexp_wave15_internal_test.go @@ -0,0 +1,132 @@ +// Copyright (c) the go-embedded-ruby/ruby authors +// +// SPDX-License-Identifier: BSD-3-Clause + +package vm + +import ( + "testing" + + "github.com/go-embedded-ruby/ruby/internal/object" +) + +// bs is a single backslash. Test sources are written with "\x5c" rather than a +// literal backslash-u so the Go-source \u escape is never triggered. +const bs = "\x5c" + +// TestSourceHasNonASCIIUnicodeEscape exercises every branch of the source scan +// that decides whether a \u escape ties a Regexp to UTF-8. Several inputs (a +// lone trailing backslash, a malformed or unterminated \u{…}, a short \uHH) can +// only be reached by calling the helper directly, since a Regexp carrying them +// would fail to compile before #encoding is ever asked. +func TestSourceHasNonASCIIUnicodeEscape(t *testing.T) { + cases := []struct { + src string + want bool + }{ + {"abc", false}, // no backslash at all + {"a" + bs, false}, // trailing backslash: nothing follows + {bs + "d+", false}, // some other escape, not \u + {bs + bs + "u{9879}", false}, // escaped backslash: the u is literal + {bs + "u{9879}", true}, // brace form, non-ASCII code point + {bs + "u{41}", false}, // brace form, ASCII code point only + {bs + "u{41 9879}", true}, // brace list: one member is non-ASCII + {bs + "u{zz}", false}, // brace body is not valid hex + {bs + "u{9879", false}, // unterminated brace form + {bs + "u9879", true}, // fixed 4-hex form, non-ASCII + {bs + "u0041", false}, // fixed 4-hex form, ASCII + {bs + "u12", false}, // fewer than 4 hex digits after \u + {bs + "u0041y" + bs + "u9879z", true}, // continues past an ASCII escape + } + for _, c := range cases { + if got := sourceHasNonASCIIUnicodeEscape(c.src); got != c.want { + t.Errorf("sourceHasNonASCIIUnicodeEscape(%q) = %v, want %v", c.src, got, c.want) + } + } +} + +// TestPatternHasBackrefOrCall exercises every branch of the linear-time scan. +func TestPatternHasBackrefOrCall(t *testing.T) { + cases := []struct { + src string + want bool + }{ + {"abc", false}, // plain literal + {"(a)" + bs + "1", true}, // numbered back-reference + {"(?a)" + bs + "k", true}, // named back-reference, angle form + {"(?a)" + bs + "k'n'", true}, // named back-reference, quote form + {"(?a)" + bs + "g", true}, // subexpression call, angle form + {"(?a)" + bs + "g'n'", true}, // subexpression call, quote form + {"[" + bs + "1]", false}, // a digit escape inside a class is octal + {"[abc]x", false}, // class open and close, then a plain char + {"a" + bs, false}, // trailing backslash: nothing follows + {"a" + bs + "d", false}, // an unrelated escape consumes its byte + {bs + "ka", false}, // \k not followed by < or ' is not a ref + } + for _, c := range cases { + if got := patternHasBackrefOrCall(c.src); got != c.want { + t.Errorf("patternHasBackrefOrCall(%q) = %v, want %v", c.src, got, c.want) + } + } +} + +// TestRegexpQuoteEncodingHelpers covers the two small helpers that decide a +// Regexp.quote / .escape result's encoding tag. +func TestRegexpQuoteEncodingHelpers(t *testing.T) { + if got := regexpQuoteResultEnc("abc", "UTF-8"); got != "US-ASCII" { + t.Errorf("regexpQuoteResultEnc(ascii) = %q, want US-ASCII", got) + } + if got := regexpQuoteResultEnc("caf\xc3\xa9", "UTF-8"); got != "UTF-8" { + t.Errorf("regexpQuoteResultEnc(non-ascii) = %q, want UTF-8", got) + } + if got := regexpQuoteResultEnc("\xff", "ASCII-8BIT"); got != "ASCII-8BIT" { + t.Errorf("regexpQuoteResultEnc(binary) = %q, want ASCII-8BIT", got) + } + if got := regexpOperandEncName(object.NewStringBytesEnc([]byte("x"), "EUC-JP")); got != "EUC-JP" { + t.Errorf("regexpOperandEncName(String) = %q, want EUC-JP", got) + } + if got := regexpOperandEncName(object.Symbol("sym")); got != "UTF-8" { + t.Errorf("regexpOperandEncName(Symbol) = %q, want UTF-8", got) + } +} + +// TestRegexpLinearTimeAndFriends drives the Ruby-visible methods so every branch +// of the native closures runs. Each expectation was checked against MRI 4.0.5. +// The VM sends #warn to the same buffer as stdout, so the flags-ignored warning +// is asserted inline before the result. +func TestRegexpLinearTimeAndFriends(t *testing.T) { + // A backslash for building Ruby source snippets without a Go \u escape. + cases := []struct{ src, want string }{ + // linear_time?: linear unless a back-reference / subexpression call. + {`p(Regexp.linear_time?(/a/))`, "true\n"}, + {`p(Regexp.linear_time?("a"))`, "true\n"}, + {`p(Regexp.linear_time?("a", Regexp::IGNORECASE))`, "true\n"}, + {`p(Regexp.linear_time?(/(a)` + bs + `1/))`, "false\n"}, + {`p(Regexp.linear_time?("(a)` + bs + bs + `1"))`, "false\n"}, + // A Regexp argument ignores flags and warns (warning shares stdout here). + {`p(Regexp.linear_time?(/a/, Regexp::IGNORECASE))`, "warning: flags ignored\ntrue\n"}, + // named_captures collects every index a repeated name owns. + {`p(/(?.)(?.)(?.)/.named_captures)`, "{\"a\" => [1, 3], \"b\" => [2]}\n"}, + // \u escape with a non-ASCII code point fixes UTF-8 (literal source). + {`p(/` + bs + `u{9879}/.encoding)`, "#\n"}, + {`p(/` + bs + `u{9879}/.fixed_encoding?)`, "true\n"}, + {`p(/A/.encoding)`, "#\n"}, + // Regexp.quote / .escape result encoding follows the input. + {`p(Regexp.quote("abc").encoding)`, "#\n"}, + {`p(Regexp.quote("café").encoding)`, "#\n"}, + {`p(Regexp.escape(:sym).encoding)`, "#\n"}, + } + for _, c := range cases { + if got := eval(t, c.src); got != c.want { + t.Errorf("src=%q\n got=%q\nwant=%q", c.src, got, c.want) + } + } +} + +// TestRegexpLinearTimeZeroArgs covers the argument-count guard. +func TestRegexpLinearTimeZeroArgs(t *testing.T) { + class, msg := evalErr(t, `Regexp.linear_time?`) + if class != "ArgumentError" || msg != "wrong number of arguments (given 0, expected 1..2)" { + t.Errorf("got %s: %q", class, msg) + } +} From b044223f885c851c225ea74b55070819ca3d1323 Mon Sep 17 00:00:00 2001 From: tannevaled Date: Sun, 6 Sep 2026 14:38:50 +0200 Subject: [PATCH 3/3] Enumerator::Lazy#each: pack multi-value yields per rb_enum_values_pack Enumerator::Lazy#each mishandled a source that yields several values at once. The lazy pipeline already threads the raw arguments of a multi-value yield (`multi`) alongside the gathered value, but the terminal #each sink dropped them, so it always passed the packed Array as a single block argument. MRI's rule (rb_enum_values_pack, confirmed against ruby 4.0.5): - a bare lazy (no ops) forwards the yielded values to the block by ordinary arity, so `{ |x| }` sees the first value and `{ |*a| }` the whole tuple; - once any op has run, a multi-value yield is packed into one Array element, which the block then receives as its single value. lazyRun's sink now carries `multi`, and #each spreads it only for a bare lazy (len(ops)==0); an op-bearing pipeline keeps the packed value. Fixes core/enumerator/each_spec (lazy variant) and the enumerable_value_packing shared examples across the lazy select/reject/drop/take/uniq/compact suites, with no regressions. core/enumerator/each_spec: pass 22 -> 24. Co-Authored-By: Claude Opus 4.8 --- internal/vm/lazy.go | 21 +++++++++++----- internal/vm/lazy_wave15_internal_test.go | 31 ++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 6 deletions(-) create mode 100644 internal/vm/lazy_wave15_internal_test.go diff --git a/internal/vm/lazy.go b/internal/vm/lazy.go index 5c05ad50..6e96b2df 100644 --- a/internal/vm/lazy.go +++ b/internal/vm/lazy.go @@ -236,9 +236,18 @@ func (vm *VM) registerLazy() { } // Incremental: drive the pipeline one element at a time so a break (or an // early-abort panic from an eager Enumerator's #first/#take) unwinds without - // materialising an unbounded source. - vm.lazyRun(l, func(v object.Value) bool { - vm.callBlock(blk, []object.Value{v}) + // materialising an unbounded source. A bare lazy (no ops) forwards a + // multi-value source yield to the block by ordinary arity, so { |x| } sees + // the first value and { |*a| } the whole tuple — as MRI's fibered lazy #each + // does. Once any op has run, MRI packs a multi-value yield into a single + // Array element (rb_enum_values_pack), so the block receives that lone value. + spreadMulti := len(l.ops) == 0 + vm.lazyRun(l, func(v object.Value, multi []object.Value) bool { + if spreadMulti && multi != nil { + vm.callBlock(blk, multi) + } else { + vm.callBlock(blk, []object.Value{v}) + } return true }) return l @@ -473,7 +482,7 @@ func (vm *VM) lazyForce(le *LazyEnum, want int) []object.Value { return nil } var out []object.Value - vm.lazyRun(le, func(v object.Value) bool { + vm.lazyRun(le, func(v object.Value, _ []object.Value) bool { out = append(out, v) return !(want >= 0 && len(out) >= want) }) @@ -499,7 +508,7 @@ type chunkState struct { // source element is threaded by feed, which recurses op-by-op so that expanding // ops (flat_map), grouping ops, and index/zip-carrying ops compose the same way // MRI's fibered lazy pipeline does. -func (vm *VM) lazyRun(le *LazyEnum, sink func(object.Value) bool) { +func (vm *VM) lazyRun(le *LazyEnum, sink func(object.Value, []object.Value) bool) { src := vm.lazySource(le.recv) n := len(le.ops) // Per-op mutable run state. @@ -564,7 +573,7 @@ func (vm *VM) lazyRun(le *LazyEnum, sink func(object.Value) bool) { } feed = func(i int, v object.Value, multi []object.Value) bool { if i == n { - if !sink(v) { + if !sink(v, multi) { stop = true return false } diff --git a/internal/vm/lazy_wave15_internal_test.go b/internal/vm/lazy_wave15_internal_test.go new file mode 100644 index 00000000..771887a6 --- /dev/null +++ b/internal/vm/lazy_wave15_internal_test.go @@ -0,0 +1,31 @@ +// Copyright (c) the go-embedded-ruby/ruby authors +// +// SPDX-License-Identifier: BSD-3-Clause + +package vm + +import "testing" + +// TestLazyEachValuePacking pins the multi-value packing of Enumerator::Lazy#each +// (rb_enum_values_pack). A bare lazy forwards a source's multiple yielded values +// to the block by ordinary arity; once any op has run the values are packed into +// one Array element. Every expectation was checked against MRI 4.0.5. +func TestLazyEachValuePacking(t *testing.T) { + multi := `Enumerator.new { |y| y.yield 1, 2 }` + cases := []struct{ src, want string }{ + // Bare lazy, multi-value source: spread by arity (spreadMulti, multi != nil). + {`a=[]; ` + multi + `.lazy.each { |x| a << x }; p a`, "[1]\n"}, + {`a=[]; ` + multi + `.lazy.each { |*x| a << x }; p a`, "[[1, 2]]\n"}, + {`a=[]; ` + multi + `.lazy.each { |x,y| a << [x,y] }; p a`, "[[1, 2]]\n"}, + // Bare lazy, single-value source: multi is nil (spreadMulti, multi == nil). + {`a=[]; [10,20].lazy.each { |x| a << x }; p a`, "[10, 20]\n"}, + // After an op, a multi-value yield is packed into one element (not spread). + {`a=[]; ` + multi + `.lazy.select { true }.each { |*z| a << z }; p a`, "[[[1, 2]]]\n"}, + {`a=[]; ` + multi + `.lazy.take(1).each { |x| a << x }; p a`, "[[1, 2]]\n"}, + } + for _, c := range cases { + if got := eval(t, c.src); got != c.want { + t.Errorf("src=%q\n got=%q\nwant=%q", c.src, got, c.want) + } + } +}