Repository navigation
Expand file tree
/
Copy pathround3_features_test.go
More file actions
443 lines (396 loc) · 12.9 KB
/
Copy pathround3_features_test.go
File metadata and controls
443 lines (396 loc) · 12.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
package parser_test
import (
"testing"
"github.com/go-ruby-parser/parser"
"github.com/go-ruby-parser/parser/ast"
)
// mustParse parses src, failing the test on error.
func mustParse(t *testing.T, src string) *ast.Program {
t.Helper()
prog, err := parser.Parse(src)
if err != nil {
t.Fatalf("Parse(%q): %v", src, err)
}
return prog
}
// --- Feature 6: character literals ?x ---
// charLitValue digs the single-character StringLit out of `p ?x` (a Call whose
// sole argument is the literal).
func charLitArg(t *testing.T, src string) string {
t.Helper()
call, ok := mustParseSingle(t, src).(*ast.Call)
if !ok {
t.Fatalf("Parse(%q): top node is not a Call", src)
}
if len(call.Args) != 1 {
t.Fatalf("Parse(%q): want 1 arg, got %d", src, len(call.Args))
}
s, ok := call.Args[0].(*ast.StringLit)
if !ok {
t.Fatalf("Parse(%q): arg is %T, want *ast.StringLit", src, call.Args[0])
}
return s.Value
}
func TestCharLiteralBasic(t *testing.T) {
cases := map[string]string{
`p ?a`: "a",
`p ?|`: "|",
`p ?/`: "/",
`p ?Z`: "Z",
`p ?1`: "1",
`p ?.`: ".",
"p ?\\n": "\n",
"p ?\\t": "\t",
"p ?\\s": " ",
"p ?\\\\": "\\",
"p ?\\e": "\x1b",
"p ?\\0": "\x00",
`p ?é`: "é",
}
for src, want := range cases {
if got := charLitArg(t, src); got != want {
t.Errorf("%q: char value = %q, want %q", src, got, want)
}
}
}
func TestCharLiteralAllEscapes(t *testing.T) {
// Exercises every backslash-escape branch of the char literal.
cases := map[string]string{
"p ?\\r": "\r",
"p ?\\a": "\x07",
"p ?\\b": "\x08",
"p ?\\v": "\x0b",
"p ?\\f": "\x0c",
"p ?\\0": "\x00",
}
for src, want := range cases {
if got := charLitArg(t, src); got != want {
t.Errorf("%q: char value = %q, want %q", src, got, want)
}
}
}
func TestCharLiteralAtExprBegin(t *testing.T) {
asn := mustParseSingle(t, `x = ?a`).(*ast.Assign)
s, ok := asn.Value.(*ast.StringLit)
if !ok || s.Value != "a" {
t.Fatalf("x = ?a: RHS = %#v, want StringLit \"a\"", asn.Value)
}
}
func TestCharLiteralWithPostfix(t *testing.T) {
// `p ?a.upcase` is `p((?a).upcase)`, not a ternary.
call := mustParseSingle(t, `p ?a.upcase`).(*ast.Call)
inner, ok := call.Args[0].(*ast.Call)
if !ok || inner.Name != "upcase" {
t.Fatalf("p ?a.upcase: arg = %#v, want .upcase call", call.Args[0])
}
if s, ok := inner.Recv.(*ast.StringLit); !ok || s.Value != "a" {
t.Fatalf("p ?a.upcase: receiver = %#v, want StringLit \"a\"", inner.Recv)
}
}
func TestQuestionStaysTernaryAfterValue(t *testing.T) {
// After a finished value the `?` is the ternary operator, never a char
// literal, even when a digit hugs it: `p 1 ?2 :3` == `p(1 ? 2 : 3)`.
call := mustParseSingle(t, `p 1 ?2 :3`).(*ast.Call)
if _, ok := call.Args[0].(*ast.If); !ok {
t.Fatalf("p 1 ?2 :3: arg = %T, want a ternary (*ast.If)", call.Args[0])
}
}
func TestTernaryWithSpacedQuestion(t *testing.T) {
// `x ? y : z` over locals stays a ternary.
prog := mustParse(t, "x=1\ny=2\np x ? y : 0")
call := prog.Body[2].(*ast.Call)
if _, ok := call.Args[0].(*ast.If); !ok {
t.Fatalf("x ? y : 0: arg = %T, want a ternary (*ast.If)", call.Args[0])
}
}
func TestQuestionNotCharLiteralForWord(t *testing.T) {
// `?ab` is not a char literal (two chars) — MRI rejects it; here `?` after a
// value position with a word also is not a single-char literal.
if _, err := parser.Parse(`p ?ab`); err == nil {
t.Fatalf("p ?ab: expected a parse error (not a char literal)")
}
}
// --- Feature 7: generalized percent-literal delimiters ---
func TestPercentDelimiterVariants(t *testing.T) {
// Any non-alphanumeric delimiter opens the literal; the result node is the
// same as the bracket-delimited form.
for _, src := range []string{
`%r"abc"`, `%r|ab|`, `%r#ab#`,
`%Q'hi'`, `%Q@hi@`, `%Q!hi!`,
`%q[x]`, `%q@x@`, `%q'x'`,
`%w'a b'`, `%w*a b*`, `%w|a b|`,
`%i<x y>`, `%i!x y!`,
`%W{a b}`, `%I<a b>`,
`%(hi)`, `%!hi!`, `%@hi@`,
`%s"sym"`, `%s|sym|`,
`%x"echo hi"`, `%x|ls|`,
} {
if _, err := parser.Parse(src); err != nil {
t.Errorf("Parse(%q): %v", src, err)
}
}
}
func TestPercentArrayQuoteDelim(t *testing.T) {
arr := mustParseSingle(t, `%w'apple pear'`).(*ast.ArrayLit)
if len(arr.Elems) != 2 {
t.Fatalf(`%%w'apple pear': got %d elems, want 2`, len(arr.Elems))
}
if s, ok := arr.Elems[0].(*ast.StringLit); !ok || s.Value != "apple" {
t.Fatalf("first elem = %#v, want StringLit \"apple\"", arr.Elems[0])
}
}
func TestPercentRegexpQuoteDelim(t *testing.T) {
re := mustParseSingle(t, `%r"a.c"i`).(*ast.RegexpLit)
if re.Source != "a.c" || re.Flags != "i" {
t.Fatalf(`%%r"a.c"i: source=%q flags=%q, want "a.c"/"i"`, re.Source, re.Flags)
}
}
// --- Feature 2: multi-line ternary ---
func TestMultiLineTernary(t *testing.T) {
for _, src := range []string{
"a=1\nb=2\nc=3\nx = a ?\n b :\n c",
"a=1\nb=2\nc=3\nx = a ? b :\n c",
"a=1\nb=2\nc=3\nx = a ?\n b : c",
"x=1\ny=2\nz=3\np x ?\ny :\nz",
} {
if _, err := parser.Parse(src); err != nil {
t.Errorf("Parse(%q): %v", src, err)
}
}
}
func TestMultiLineTernaryShape(t *testing.T) {
prog := mustParse(t, "a=1\nb=2\nc=3\nx = a ?\n b :\n c")
asn := prog.Body[3].(*ast.Assign)
if _, ok := asn.Value.(*ast.If); !ok {
t.Fatalf("multi-line ternary RHS = %T, want *ast.If", asn.Value)
}
}
// --- Feature 3: adjacent string-literal concatenation ---
func TestAdjacentStringConcat(t *testing.T) {
s, ok := mustParseSingle(t, `"a" "b" "c"`).(*ast.StringLit)
if !ok || s.Value != "abc" {
t.Fatalf(`"a" "b" "c" = %#v, want StringLit "abc"`, mustParseSingle(t, `"a" "b" "c"`))
}
}
func TestAdjacentStringConcatSingleQuote(t *testing.T) {
s := mustParseSingle(t, `'x' 'y'`).(*ast.StringLit)
if s.Value != "xy" {
t.Fatalf(`'x' 'y' = %q, want "xy"`, s.Value)
}
}
func TestAdjacentStringConcatBackslashContinued(t *testing.T) {
s := mustParseSingle(t, "\"a\" \\\n \"b\"").(*ast.StringLit)
if s.Value != "ab" {
t.Fatalf(`backslash-continued concat = %q, want "ab"`, s.Value)
}
}
func TestAdjacentStringConcatWithInterp(t *testing.T) {
// A plain piece adjacent to an interpolated one folds into one StrInterp.
for _, src := range []string{
`"a" "b#{1}"`,
`"a#{1}" "b"`,
`"a#{1}" "b#{2}"`,
} {
n := mustParseSingle(t, src)
if _, ok := n.(*ast.StrInterp); !ok {
t.Errorf("Parse(%q): node = %T, want *ast.StrInterp", src, n)
}
}
}
// --- Feature 1: string-adjacent command argument (no space) ---
func TestHuggingStringCommandArg(t *testing.T) {
for _, src := range []string{
`foo"bar"`,
`p"hello"`,
`assert"x", y`,
`foo"a""b"`,
`foo"a#{1}"`,
} {
call, ok := mustParseSingle(t, src).(*ast.Call)
if !ok {
t.Errorf("Parse(%q): node = %T, want *ast.Call", src, mustParseSingle(t, src))
continue
}
if len(call.Args) == 0 {
t.Errorf("Parse(%q): call has no args", src)
}
}
}
func TestHuggingStringCommandArgWithBlock(t *testing.T) {
call := mustParseSingle(t, `step"Ensure something" do; end`).(*ast.Call)
if call.Name != "step" || call.Block == nil {
t.Fatalf("step\"...\" do…end: name=%q block=%v, want step + a block", call.Name, call.Block)
}
if s, ok := call.Args[0].(*ast.StringLit); !ok || s.Value != "Ensure something" {
t.Fatalf("step arg = %#v, want StringLit", call.Args[0])
}
}
func TestHuggingStringOnLocalIsCall(t *testing.T) {
// `x"y"` is a command call even though x is a local (MRI: x("y")).
prog := mustParse(t, "x = 1\nx\"y\"")
call, ok := prog.Body[1].(*ast.Call)
if !ok || call.Name != "x" {
t.Fatalf("x\"y\" = %#v, want a Call named x", prog.Body[1])
}
}
func TestHuggingStringOnReceiverAndConst(t *testing.T) {
for _, src := range []string{`obj.foo"bar"`, `Foo"bar"`} {
if _, ok := mustParseSingle(t, src).(*ast.Call); !ok {
t.Errorf("Parse(%q): node = %T, want *ast.Call", src, mustParseSingle(t, src))
}
}
}
// --- Feature 9: block params on a continued line ---
func TestBlockParamsOnContinuedLine(t *testing.T) {
for _, src := range []string{
"foo {\n|x| x }",
"foo do\n|a, b|\na + b\nend",
"[1].each {\n |x|\n p x\n}",
"foo do\n\n|compare, target, success|\nnil\nend",
} {
if _, err := parser.Parse(src); err != nil {
t.Errorf("Parse(%q): %v", src, err)
}
}
}
func TestBlockParamsContinuedShape(t *testing.T) {
call := mustParseSingle(t, "foo do\n|a, b|\na\nend").(*ast.Call)
if call.Block == nil {
t.Fatal("foo do\\n|a,b| …: no block")
}
if len(call.Block.Params) != 2 || call.Block.Params[0] != "a" || call.Block.Params[1] != "b" {
t.Fatalf("block params = %v, want [a b]", call.Block.Params)
}
}
func TestBlockWithoutParamsStillWorks(t *testing.T) {
// A body that simply starts on the next line must not be read as params.
for _, src := range []string{"foo {\nx }", "foo {\n}", "foo do\nx\nend"} {
if _, err := parser.Parse(src); err != nil {
t.Errorf("Parse(%q): %v", src, err)
}
}
}
// TestBlockOpenerNewlinesToEOF exercises firstSignificantIs's run-to-EOF path: an
// opener followed only by newlines (an unterminated block) still scans for a `|`,
// finds none, and surfaces a clean parse error rather than crashing.
func TestBlockOpenerNewlinesToEOF(t *testing.T) {
if _, err := parser.Parse("foo {\n\n"); err == nil {
t.Fatalf("unterminated block: expected a parse error")
}
}
// --- Feature 5: control-flow + modifier inside parens ---
func TestControlFlowInsideParens(t *testing.T) {
for _, src := range []string{
`(set_param(p) and return) unless cur`,
`[1].each { ( x or next )[1] }`,
`(expr if cond)`,
`(x if y) || z`,
`[1].each { (m.match(s) or next)[1] }`,
} {
if _, err := parser.Parse(src); err != nil {
t.Errorf("Parse(%q): %v", src, err)
}
}
}
// --- Feature 8: control-flow keyword as expression operand ---
func TestControlFlowKeywordAsOperand(t *testing.T) {
for _, src := range []string{
`def f; x || return; end`,
`[1].each { |x| x || next }`,
`[1].each { |x| x || break }`,
`while true; x || break; end`,
`a = b || return`,
`def f; x or return; end`,
`def f; x && return; end`,
} {
if _, err := parser.Parse(src); err != nil {
t.Errorf("Parse(%q): %v", src, err)
}
}
}
func TestControlFlowOperandRejectsValue(t *testing.T) {
// MRI: a value after the jump in operand position is a syntax error.
if _, err := parser.Parse(`def f; x || return 5; end`); err == nil {
t.Fatalf("x || return 5: expected a parse error")
}
}
func TestControlFlowOperandShape(t *testing.T) {
ifn := mustParseSingle(t, "def f; x || return; end").(*ast.MethodDef)
be := ifn.Body[0].(*ast.BinaryExpr)
if _, ok := be.Right.(*ast.Return); !ok {
t.Fatalf("RHS of || = %T, want *ast.Return", be.Right)
}
}
// --- Feature 4: assignment inside a condition / expression ---
func TestInlineAssignmentInCondition(t *testing.T) {
for _, src := range []string{
`if a && b = c; end`,
`if ct && m = RE.match(s); end`,
`if a || b = c; end`,
`while x && line = gets; end`,
`r = a && @b = 1`,
`if a && @@c = 2; end`,
`if a && $g = 3; end`,
`if a && K = 4; end`,
`if a && h[k] = 5; end`,
`if a && o.attr = 6; end`,
} {
if _, err := parser.Parse(src); err != nil {
t.Errorf("Parse(%q): %v", src, err)
}
}
}
func TestInlineAssignmentShape(t *testing.T) {
// `if a && b = c` is `if a && (b = c)`.
ifn := mustParseSingle(t, "if a && b = c; end").(*ast.If)
be := ifn.Cond.(*ast.BinaryExpr)
if be.Op != "&&" {
t.Fatalf("cond op = %q, want &&", be.Op)
}
if _, ok := be.Right.(*ast.Assign); !ok {
t.Fatalf("RHS of && = %T, want *ast.Assign", be.Right)
}
}
func TestInlineAssignmentToExistingLocal(t *testing.T) {
// When the target is already a known local it parses as a VarRef before the
// `=`, exercising maybeInlineAssign's VarRef branch: `x` is a local, then
// `a && x = 1` assigns to it.
prog := mustParse(t, "x = 0\nif a && x = 1\nend")
ifn := prog.Body[1].(*ast.If)
if _, ok := ifn.Cond.(*ast.BinaryExpr).Right.(*ast.Assign); !ok {
t.Fatalf("a && x = 1 (x local): RHS not an *ast.Assign")
}
}
func TestInlineAssignmentLeavesNonTargetAlone(t *testing.T) {
// An `=` after a non-assignable operand (a literal, or a call with args) is
// not an inline assignment; the parser surfaces an ordinary error instead of
// silently consuming it (maybeInlineAssign's final return-node path).
for _, src := range []string{
`if a && 1 = 2; end`,
`if a && foo(x) = 2; end`,
} {
if _, err := parser.Parse(src); err == nil {
t.Errorf("Parse(%q): expected a parse error", src)
}
}
}
func TestInlineAssignmentDoesNotEatComparisons(t *testing.T) {
// `==`, `=>`, `=~` must not be swallowed as assignments.
for _, src := range []string{`p(a == b)`, `p(a =~ b)`, `x == y`} {
if _, err := parser.Parse(src); err != nil {
t.Errorf("Parse(%q): %v", src, err)
}
}
}
func TestPercentDoesNotBreakModuloOrOpAssign(t *testing.T) {
// `%=` stays a compound assignment; `a % 3` stays modulo.
prog := mustParse(t, "a = 10\na %= 3")
if _, ok := prog.Body[1].(*ast.OpAssign); !ok {
t.Fatalf("a %%= 3: node = %T, want *ast.OpAssign", prog.Body[1])
}
prog = mustParse(t, "a = 10\np a % 3")
call := prog.Body[1].(*ast.Call)
if _, ok := call.Args[0].(*ast.BinaryExpr); !ok {
t.Fatalf("a %% 3: arg = %T, want *ast.BinaryExpr (modulo)", call.Args[0])
}
}