From 380cf9c44bee2216667329bf81689a58738d0952 Mon Sep 17 00:00:00 2001 From: Tejas Date: Mon, 23 Nov 2026 15:44:48 +0530 Subject: [PATCH 01/39] feat(pir): print a plan's source as the statement's own lines MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A plan's source was one quoted line, so every quote inside it was escaped and a block-layout literal was a single line of \n sequences. The label now stands alone and the statement's lines sit one level in, as its author wrote them: assign scores source scores = [ : Name Score "Ada" 10 ] Within a line every control character is still escaped, so a source never goes invisible and never breaks the layout; only a line break becomes a line. That drops the escaping from 126 of the 129 source lines the tests and docs hold, 43 of which carried an escaped quote. A node's operand keeps the opposite rule, one line with its line breaks escaped, which §12 now states separately. The two disagree for a string literal that spans lines: the source shows the continuation shifted to the section's indent, while the operand beside it is exact, and TestPlanGoldenMultilineString pins both spellings together. Machine code is untouched: all 89 fixture executables have an identical __text, and with every source section elided the plan text over master's fixtures is byte-identical, 4,115 sections on each side. Co-Authored-By: Claude Opus 5 --- compiler/pir_test.go | 289 ++++++++++++++++++++++++++++-------------- docs/Pluto IR Plan.md | 54 +++++--- emit_pir_test.go | 21 ++- pir/pir_test.go | 71 +++++++---- pir/print.go | 15 ++- 5 files changed, 305 insertions(+), 145 deletions(-) diff --git a/compiler/pir_test.go b/compiler/pir_test.go index 962b7db7..8ce44a75 100644 --- a/compiler/pir_test.go +++ b/compiler/pir_test.go @@ -82,7 +82,8 @@ s`) require.Equal(t, []string{"assign a", "assign b", "assign a, b", "assign _", "assign r", "assign s"}, planLabels(plans)) require.Equal(t, `assign a, b - source "a, b = b, a" + source + a, b = b, a execute %t0 = eval I64 b @@ -94,7 +95,8 @@ s`) `, plans[2].Render(false)) require.Equal(t, `assign b - source "b = (a + (2 * 3))" + source + b = (a + (2 * 3)) execute %t0 = eval I64 a + (2 * 3) @@ -104,7 +106,8 @@ s`) `, plans[1].Render(true)) require.Equal(t, `assign _ - source "_ = 7" + source + _ = 7 execute %t0 = eval I64 7 @@ -114,7 +117,8 @@ s`) `, plans[3].Render(false)) require.Equal(t, `assign r - source "r = 0:10:2" + source + r = 0:10:2 execute %t0 = eval I64:I64:I64 0:10:2 @@ -124,7 +128,8 @@ s`) `, plans[4].Render(false)) require.Equal(t, `assign s - source "s = r" + source + s = r execute %t0 = eval I64:I64:I64 r @@ -358,7 +363,8 @@ func TestPlanGoldenRangeDiscard(t *testing.T) { plans := compileScriptPlans(t, ctx, "planRangeDiscard", "", "_ = 0:3") require.Equal(t, []string{"assign _"}, planLabels(plans)) require.Equal(t, `assign _ - source "_ = 0:3" + source + _ = 0:3 execute %t0 = eval I64:I64:I64 0:3 @@ -376,7 +382,8 @@ func TestPlanGoldenUnicode(t *testing.T) { plans := compileScriptPlans(t, ctx, "planUnicode", "", "π = 3.14\nτ = π\nτ") require.Equal(t, []string{"assign π", "assign τ"}, planLabels(plans)) require.Equal(t, `assign π - source "π = 3.14" + source + π = 3.14 execute %t0 = eval F64 3.14 @@ -385,7 +392,8 @@ func TestPlanGoldenUnicode(t *testing.T) { π = %t0 `, plans[0].Render(false)) require.Equal(t, `assign τ - source "τ = π" + source + τ = π execute %t0 = eval F64 π @@ -403,7 +411,8 @@ func TestPlanGoldenPrefix(t *testing.T) { plans := compileScriptPlans(t, ctx, "planPrefix", "", "a = 1\nn = -a\nn") require.Equal(t, []string{"assign a", "assign n"}, planLabels(plans)) require.Equal(t, `assign n - source "n = (-a)" + source + n = (-a) execute %t0 = eval I64 -a @@ -422,7 +431,8 @@ func TestPlanGoldenBareBindings(t *testing.T) { plans := compileScriptPlans(t, ctx, "planBare", "", "t0 = 1\nx = t0\ndiscard = 2\n_ = 3\nx, discard") require.Equal(t, []string{"assign t0", "assign x", "assign discard", "assign _"}, planLabels(plans)) require.Equal(t, `assign x - source "x = t0" + source + x = t0 execute %t0 = eval I64 t0 @@ -431,7 +441,8 @@ func TestPlanGoldenBareBindings(t *testing.T) { x = %t0 `, plans[1].Render(false)) require.Equal(t, `assign t0 - source "t0 = 1" + source + t0 = 1 execute %t0 = eval I64 1 @@ -440,7 +451,8 @@ func TestPlanGoldenBareBindings(t *testing.T) { t0 = %t0 `, plans[0].Render(false)) require.Equal(t, `assign discard - source "discard = 2" + source + discard = 2 execute %t0 = eval I64 2 @@ -449,7 +461,8 @@ func TestPlanGoldenBareBindings(t *testing.T) { discard = %t0 `, plans[2].Render(false)) require.Equal(t, `assign _ - source "_ = 3" + source + _ = 3 execute %t0 = eval I64 3 @@ -471,7 +484,8 @@ h1, h2 = h2, h1 h1, h2`) require.Equal(t, []string{"assign h1", "assign h2", "assign h1, h2"}, planLabels(plans)) require.Equal(t, `assign h1 - source "h1 = (\"foo\" ⊕ \"bar\")" + source + h1 = ("foo" ⊕ "bar") execute %t0 = eval owned Str "foo" ⊕ "bar" @@ -480,7 +494,8 @@ h1, h2`) h1 = %t0 [move] `, plans[0].Render(true)) require.Equal(t, `assign h1, h2 - source "h1, h2 = h2, h1" + source + h1, h2 = h2, h1 execute %t0 = eval borrowed Str h2 @@ -504,7 +519,8 @@ d1, d2 d1, d2 = d1, d1 d1, d2`) require.Equal(t, `assign d1, d2 - source "d1, d2 = d1, d1" + source + d1, d2 = d1, d1 execute %t0 = eval borrowed Str d1 @@ -534,7 +550,8 @@ x, y = y ⊕ "!", x x, y`) require.Equal(t, []string{"assign x", "assign x", "assign _", "assign _", "assign y", "assign x, y"}, planLabels(plans)) require.Equal(t, `assign x - source "x = (x ⊕ \"!\")" + source + x = (x ⊕ "!") execute %t0 = eval owned Str x ⊕ "!" @@ -544,7 +561,8 @@ x, y`) drop x [old] `, plans[1].Render(true)) require.Equal(t, `assign _ - source "_ = (x ⊕ \"?\")" + source + _ = (x ⊕ "?") execute %t0 = eval owned Str x ⊕ "?" @@ -554,7 +572,8 @@ x, y`) drop %t0 `, plans[2].Render(true)) require.Equal(t, `assign _ - source "_ = x" + source + _ = x execute %t0 = eval borrowed Str x @@ -563,7 +582,8 @@ x, y`) _ = %t0 `, plans[3].Render(true)) require.Equal(t, `assign x, y - source "x, y = (y ⊕ \"!\"), x" + source + x, y = (y ⊕ "!"), x execute %t0 = eval owned Str y ⊕ "!" @@ -591,7 +611,8 @@ t = g s, t`) require.Equal(t, []string{"assign s", "assign s", "assign g", "assign t"}, planLabels(plans)) require.Equal(t, `assign s - source "s = \"hi\"" + source + s = "hi" execute %t0 = eval Str "hi" @@ -600,7 +621,8 @@ s, t`) s = %t0 [copy] `, plans[0].Render(true)) require.Equal(t, `assign t - source "t = g" + source + t = g execute %t0 = eval Str g @@ -626,7 +648,8 @@ arr1 = []0 arr1, arr2`) require.Equal(t, []string{"assign arr1", "assign arr2", "assign arr2", "assign arr1"}, planLabels(plans)) require.Equal(t, `assign arr1 - source "arr1 = [1 2 3]" + source + arr1 = [1 2 3] execute %t0 = eval owned [I64] [1 2 3] @@ -635,7 +658,8 @@ arr1, arr2`) arr1 = %t0 [move] `, plans[0].Render(true)) require.Equal(t, `assign arr2 - source "arr2 = arr1" + source + arr2 = arr1 execute %t0 = eval borrowed [I64] arr1 @@ -644,7 +668,8 @@ arr1, arr2`) arr2 = %t0 [copy] `, plans[1].Render(true)) require.Equal(t, `assign arr2 - source "arr2 = [4 5 6]" + source + arr2 = [4 5 6] execute %t0 = eval owned [I64] [4 5 6] @@ -654,7 +679,8 @@ arr1, arr2`) drop arr2 [old] `, plans[2].Render(true)) require.Equal(t, `assign arr1 - source "arr1 = []0" + source + arr1 = []0 execute %t0 = eval owned [I64] []0 @@ -689,7 +715,8 @@ t2 = scores n, a, s2.age, col, t2`) require.Equal(t, []string{"assign n", "assign a", "assign s2", "assign scores", "assign col", "assign t2"}, planLabels(plans)) require.Equal(t, `assign n - source "n = p.name" + source + n = p.name execute %t0 = eval Str p.name @@ -698,7 +725,8 @@ n, a, s2.age, col, t2`) n = %t0 `, plans[0].Render(true)) require.Equal(t, `assign s2 - source "s2 = p" + source + s2 = p execute %t0 = eval Person{name:Str age:I64} p @@ -707,7 +735,11 @@ n, a, s2.age, col, t2`) s2 = %t0 `, plans[2].Render(true)) require.Equal(t, `assign scores - source "scores = [\n : Name Score\n \"Ada\" 10\n]" + source + scores = [ + : Name Score + "Ada" 10 + ] execute %t0 = eval owned Table[Name:Str Score:I64] [\n : Name Score\n "Ada" 10\n] @@ -716,7 +748,8 @@ n, a, s2.age, col, t2`) scores = %t0 [move] `, plans[3].Render(true)) require.Equal(t, `assign col - source "col = scores.Score" + source + col = scores.Score execute %t0 = eval owned [I64] scores.Score @@ -725,7 +758,8 @@ n, a, s2.age, col, t2`) col = %t0 [move] `, plans[4].Render(true)) require.Equal(t, `assign t2 - source "t2 = scores" + source + t2 = scores execute %t0 = eval borrowed Table[Name:Str Score:I64] scores @@ -752,7 +786,8 @@ other = "new" copy, other, text`) require.Equal(t, []string{"assign text", "assign text, other", "assign copy", "assign other"}, planLabels(plans)) require.Equal(t, `assign text, other - source "text, other = (text ⊕ \"!\"), text" + source + text, other = (text ⊕ "!"), text execute %t0 = eval owned Str text ⊕ "!" @@ -763,7 +798,8 @@ copy, other, text`) other = %t1 [move] `, plans[1].Render(true)) require.Equal(t, `assign copy - source "copy = other" + source + copy = other execute %t0 = eval borrowed Str other @@ -772,7 +808,8 @@ copy, other, text`) copy = %t0 [copy] `, plans[2].Render(true)) require.Equal(t, `assign other - source "other = \"new\"" + source + other = "new" execute %t0 = eval Str "new" @@ -786,14 +823,17 @@ copy, other, text`) } // Plan §12: a multiline string literal is one eval operand on one line, its -// control characters escaped; the source line is quoted the same way. +// control characters escaped, while the source prints the statement's own +// lines, so the two spellings of one string sit together. func TestPlanGoldenMultilineString(t *testing.T) { ctx := llvm.NewContext() defer ctx.Dispose() plans := compileScriptPlans(t, ctx, "planMultiline", "", "s = \"line one\nline two\"\ns") require.Equal(t, `assign s - source "s = \"line one\nline two\"" + source + s = "line one + line two" execute %t0 = eval Str "line one\nline two" @@ -823,7 +863,8 @@ direct = scores.Value col, direct, taken, headerOnly`) require.Equal(t, []string{"assign scores", "assign headerOnly", "assign taken", "assign headerOnly", "assign col", "assign direct"}, planLabels(plans)) require.Equal(t, `assign col - source "col = taken.Value" + source + col = taken.Value execute %t0 = eval owned [I64] taken.Value @@ -864,7 +905,8 @@ copied, tag = Copy(p) d, l, r, n, copied.age, tag`) require.Equal(t, []string{"assign d", "assign d", "assign l, r", "assign l, _, n", "assign copied, tag"}, planLabels(plans)) require.Equal(t, `assign d - source "d = (Twice(d) + 1)" + source + d = (Twice(d) + 1) execute %t0 = eval I64 Twice(d) + 1 @@ -873,7 +915,8 @@ d, l, r, n, copied.age, tag`) d = %t0 `, plans[1].Render(true)) require.Equal(t, `assign l, r - source "l, r = twoStr(\"a\", \"b\")" + source + l, r = twoStr("a", "b") execute %t0 = eval owned Str, owned Str twoStr("a", "b") @@ -883,7 +926,8 @@ d, l, r, n, copied.age, tag`) r = %t0#1 [move] `, plans[2].Render(true)) require.Equal(t, `assign l, _, n - source "l, _, n = twoStr(l, r), 9" + source + l, _, n = twoStr(l, r), 9 execute %t0 = eval owned Str, owned Str twoStr(l, r) @@ -897,7 +941,8 @@ d, l, r, n, copied.age, tag`) drop l [old] `, plans[3].Render(true)) require.Equal(t, `assign copied, tag - source "copied, tag = Copy(p)" + source + copied, tag = Copy(p) execute %t0 = eval Person{name:Str age:I64}, Str Copy(p) @@ -965,7 +1010,8 @@ n, o, k, p, q, one, acc`) // A function local is a local target; a function body's plan sits one // level in. require.Equal(t, ` assign t - source "t = (a + 1)" + source + t = (a + 1) execute %t0 = eval I64 a + 1 @@ -975,7 +1021,8 @@ n, o, k, p, q, one, acc`) `, plans[8].Render(false)) // Row 14: a direct scalar output is a plain store. require.Equal(t, ` assign res - source "res = (t * 2)" + source + res = (t * 2) execute %t0 = eval I64 t * 2 @@ -985,7 +1032,8 @@ n, o, k, p, q, one, acc`) `, plans[9].Render(true)) // Row 14i: a heap output takes an owned outcome and releases what it held. require.Equal(t, ` assign out - source "out = (s ⊕ \"!\")" + source + out = (s ⊕ "!") execute %t0 = eval owned Str s ⊕ "!" @@ -996,7 +1044,8 @@ n, o, k, p, q, one, acc`) `, plans[10].Render(true)) // A borrowed input survives the call, so the output gets its own copy. require.Equal(t, ` assign kept - source "kept = s" + source + kept = s execute %t0 = eval borrowed Str s @@ -1007,7 +1056,8 @@ n, o, k, p, q, one, acc`) `, plans[11].Render(true)) // A static string entering an output whose type owns heap is copied. require.Equal(t, ` assign out - source "out = \"none\"" + source + out = "none" execute %t0 = eval Str "none" @@ -1018,7 +1068,8 @@ n, o, k, p, q, one, acc`) `, plans[12].Render(true)) // Row 14a: a rejected gate leaves an output holding what it held. require.Equal(t, ` assign out - source "out = (n > 0) (s ⊕ \"?\")" + source + out = (n > 0) (s ⊕ "?") execute %t0 = check I64 n > 0 @@ -1067,7 +1118,8 @@ x, fresh, t, u, hc, bc`) // An existing target keeps its value where the gate rejects. require.Equal(t, `assign x - source "x = (n > 0) 5" + source + x = (n > 0) 5 execute %t0 = check I64 n > 0 @@ -1079,7 +1131,8 @@ x, fresh, t, u, hc, bc`) `, plans[2].Render(true)) // A fresh target holds zero there, and has no old value to release. require.Equal(t, `assign fresh - source "fresh = (n > 9) t" + source + fresh = (n > 9) t execute %t0 = check I64 n > 9 @@ -1092,7 +1145,8 @@ x, fresh, t, u, hc, bc`) // A gate rejects both mappings or neither, so each borrow still takes its // owner's old value. require.Equal(t, `assign t, u - source "t, u = (n > 0) u, t" + source + t, u = (n > 0) u, t execute %t0 = check I64 n > 0 @@ -1107,7 +1161,8 @@ x, fresh, t, u, hc, bc`) // A read in the condition skips the check, and a first sits in the gate's // region like any value. require.Equal(t, `assign x - source "x = (arr[1] > (-1)) (arr[9] || 8)" + source + x = (arr[1] > (-1)) (arr[9] || 8) execute %t0 = check I64 arr[1] > (-1) [on-oob=skip] @@ -1123,7 +1178,8 @@ x, fresh, t, u, hc, bc`) `, plans[8].Render(false)) // The gate only tests the check, so the string the check built is released. require.Equal(t, `assign hc - source "hc = (MkStr(n) > \"a\") 7" + source + hc = (MkStr(n) > "a") 7 execute %t0 = check owned Str MkStr(n) > "a" @@ -1136,7 +1192,8 @@ x, fresh, t, u, hc, bc`) `, plans[9].Render(true)) // A binding the check read stays its owner's. require.Equal(t, `assign bc - source "bc = (t > \"abc\") 1" + source + bc = (t > "abc") 1 execute %t0 = check borrowed(t) Str t > "abc" @@ -1149,7 +1206,8 @@ x, fresh, t, u, hc, bc`) // Row 5e: a discard keeps nothing, so it carries no policy; what its eval // built is released where the gate admitted it. require.Equal(t, `assign _ - source "_ = (n > 0) MkStr(n)" + source + _ = (n > 0) MkStr(n) execute %t0 = check I64 n > 0 @@ -1223,7 +1281,8 @@ x, three, t, u, lb`) // and the gate takes it. Each check is only tested, so the string each // built is released. require.Equal(t, `assign three - source "three = (n > 0) && (MkStr(n) > \"a\") && (MkStr(x) > \"a\") 7" + source + three = (n > 0) && (MkStr(n) > "a") && (MkStr(x) > "a") 7 execute %t0 = @@ -1244,7 +1303,8 @@ x, three, t, u, lb`) // A value last moves what its final side built, and what its check built // is only tested. require.Equal(t, `assign t - source "t = ((MkStr(n) > \"a\") && MkStr(x))" + source + t = ((MkStr(n) > "a") && MkStr(x)) execute %t0 = @@ -1261,7 +1321,8 @@ x, three, t, u, lb`) // A last may skip its own mapping, so neither borrow takes the other's // old value: where a gate moves both strings of a swap, this copies both. require.Equal(t, `assign t, u - source "t, u = ((n > 0) && u), t" + source + t, u = ((n > 0) && u), t execute %t0 = @@ -1280,7 +1341,8 @@ x, three, t, u, lb`) // A chain in value position is one last, and a read in its final side // skips it where the read fails. require.Equal(t, `assign x - source "x = (((n > 0) && (n > 1)) && arr[9])" + source + x = (((n > 0) && (n > 1)) && arr[9]) execute %t0 = @@ -1296,7 +1358,8 @@ x, three, t, u, lb`) `, plans[8].Render(true)) // A last in a gate's region is numbered after the gate's check. require.Equal(t, `assign x - source "x = (n > 0) ((n > 2) && 10)" + source + x = (n > 0) ((n > 2) && 10) execute %t0 = check I64 n > 0 @@ -1312,7 +1375,8 @@ x, three, t, u, lb`) `, plans[9].Render(true)) // A discard keeps nothing: what the final side built is released. require.Equal(t, `assign _ - source "_ = ((n > 0) && MkStr(n))" + source + _ = ((n > 0) && MkStr(n)) execute %t0 = @@ -1328,7 +1392,8 @@ x, three, t, u, lb`) // A last that ends in a comparison yields that check's left operand, and // what the check built is released where it failed. require.Equal(t, `assign lb - source "lb = ((n > 0) && (MkStr(n) > \"a\"))" + source + lb = ((n > 0) && (MkStr(n) > "a")) execute %t0 = @@ -1371,7 +1436,8 @@ x, g, s`) }, planOwners(plans)) require.Equal(t, `assign x - source "x = (a > 2)" + source + x = (a > 2) execute %t0 = check I64 a > 2 @@ -1380,7 +1446,8 @@ x, g, s`) x = %t0 [on-skip=keep] `, plans[3].Render(false)) require.Equal(t, `assign g - source "g = (n > 0) (a > 2)" + source + g = (n > 0) (a > 2) execute %t0 = check I64 n > 0 @@ -1391,7 +1458,8 @@ x, g, s`) g = %t1 [on-skip=zero] `, plans[4].Render(false)) require.Equal(t, `assign s - source "s = (MkStr(a) > \"zzz\")" + source + s = (MkStr(a) > "zzz") execute %t0 = check owned Str MkStr(a) > "zzz" @@ -1442,7 +1510,8 @@ m`) // A print of literals alone has no eval. require.Equal(t, `print - source "\"hello\"" + source + "hello" execute print "hello" @@ -1451,7 +1520,8 @@ m`) // place and is never built as one string, where the same literal as a // value is an owned string. require.Equal(t, `print - source "\"n: -n\", n" + source + "n: -n", n execute %t0 = eval I64 n @@ -1459,7 +1529,8 @@ m`) `, plans[3].Render(true)) // The invocation reads a binding's heap value and takes a temporary's. require.Equal(t, `print - source "h, (h ⊕ \"!\")" + source + h, (h ⊕ "!") execute %t0 = eval borrowed Str h @@ -1468,14 +1539,16 @@ m`) `, plans[4].Render(true)) // Row 29c: every slot of a multi-output call prints, each owned one taken. require.Equal(t, `print - source "Echo(h)" + source + Echo(h) execute %t0 = eval owned Str, owned Str Echo(h) print %t0#0 [move], %t0#1 [move] `, plans[5].Render(true)) require.Equal(t, `print - source "([1 2] ⊕ [3])" + source + ([1 2] ⊕ [3]) execute %t0 = eval owned [I64] [1 2] ⊕ [3] @@ -1483,7 +1556,8 @@ m`) `, plans[6].Render(true)) // A print in a function body sits in that function's block. require.Equal(t, ` print - source "\"in:\", a" + source + "in:", a execute %t0 = eval I64 a @@ -1535,7 +1609,8 @@ keep, fresh, s, h1, h2, r`) // An existing target keeps its value. require.Equal(t, `assign keep - source "keep = (keep * arr[5])" + source + keep = (keep * arr[5]) execute %t0 = eval I64 keep * arr[5] [on-oob=skip] @@ -1547,7 +1622,8 @@ keep, fresh, s, h1, h2, r`) // stays in the read's eval, whose own order decides whether it runs // (tests/cond/value_cond_expr pins that at run time). require.Equal(t, `assign fresh - source "fresh = (Loud(1) + arr[9])" + source + fresh = (Loud(1) + arr[9]) execute %t0 = eval I64 Loud(1) + arr[9] [on-oob=skip] @@ -1558,7 +1634,8 @@ keep, fresh, s, h1, h2, r`) // What a skipped outcome built is released, and the old value only where // the mapping replaced it. require.Equal(t, `assign s - source "s = (s ⊕ sarr[9])" + source + s = (s ⊕ sarr[9]) execute %t0 = eval owned Str s ⊕ sarr[9] [on-oob=skip] @@ -1570,7 +1647,8 @@ keep, fresh, s, h1, h2, r`) `, plans[6].Render(true)) // Row 5d: a discard keeps nothing, and its outcome is released either way. require.Equal(t, `assign _ - source "_ = sarr[1]" + source + _ = sarr[1] execute %t0 = eval owned Str sarr[1] [on-oob=skip] @@ -1581,7 +1659,8 @@ keep, fresh, s, h1, h2, r`) `, plans[7].Render(true)) // A swap beside a read still moves: both of its mappings always commit. require.Equal(t, `assign h1, h2, keep - source "h1, h2, keep = h2, h1, arr[arr[9]]" + source + h1, h2, keep = h2, h1, arr[arr[9]] execute %t0 = eval borrowed Str h2 @@ -1595,7 +1674,8 @@ keep, fresh, s, h1, h2, r`) `, plans[10].Render(true)) // h2's replacement may skip, so h1 cannot take the value h2 holds. require.Equal(t, `assign h1, h2 - source "h1, h2 = h2, sarr[9]" + source + h1, h2 = h2, sarr[9] execute %t0 = eval borrowed Str h2 @@ -1610,7 +1690,8 @@ keep, fresh, s, h1, h2, r`) `, plans[12].Render(true)) // An output is never fresh, so it keeps the value it holds. require.Equal(t, ` assign res - source "res = v[0]" + source + res = v[0] execute %t0 = eval I64 v[0] [on-oob=skip] @@ -1658,7 +1739,8 @@ a, s, c, g, p, q, r, w`) // A fresh target and an existing one read alike: the first always yields. require.Equal(t, `assign a - source "a = (arr[9] || (-1))" + source + a = (arr[9] || (-1)) execute %t0 = @@ -1673,7 +1755,8 @@ a, s, c, g, p, q, r, w`) // The read's copy moves and the binding is copied; what the failed read // built is released where the fallback ran. require.Equal(t, `assign s - source "s = (sarr[9] || h)" + source + s = (sarr[9] || h) execute %t0 = @@ -1689,7 +1772,8 @@ a, s, c, g, p, q, r, w`) `, plans[6].Render(true)) // A chain is one first, however it is grouped. require.Equal(t, `assign c - source "c = ((arr[9] || arr[8]) || (-3))" + source + c = ((arr[9] || arr[8]) || (-3)) execute %t0 = @@ -1706,7 +1790,8 @@ a, s, c, g, p, q, r, w`) // A last side that can fail skips the outcome, so the target keeps its // value. require.Equal(t, `assign g - source "g = (arr[9] || arr[8])" + source + g = (arr[9] || arr[8]) execute %t0 = @@ -1720,7 +1805,8 @@ a, s, c, g, p, q, r, w`) `, plans[9].Render(false)) // A discard releases each owned side where it ran. require.Equal(t, `assign _ - source "_ = (sarr[9] || (h ⊕ \"?\"))" + source + _ = (sarr[9] || (h ⊕ "?")) execute %t0 = @@ -1736,7 +1822,8 @@ a, s, c, g, p, q, r, w`) `, plans[10].Render(true)) // The eval after a first takes the ID after its sides. require.Equal(t, `assign p, q - source "p, q = (arr[9] || (-1)), 5" + source + p, q = (arr[9] || (-1)), 5 execute %t0 = @@ -1752,7 +1839,8 @@ a, s, c, g, p, q, r, w`) `, plans[11].Render(false)) // A side may wrap its read, and fails where the read does. require.Equal(t, `assign w - source "w = ((arr[9] + 1) || (-1))" + source + w = ((arr[9] + 1) || (-1)) execute %t0 = @@ -1765,7 +1853,8 @@ a, s, c, g, p, q, r, w`) w = %t0 `, plans[13].Render(false)) require.Equal(t, ` assign res - source "res = (v[i] || (-1))" + source + res = (v[i] || (-1)) execute %t0 = @@ -1816,7 +1905,8 @@ s, t, h, g`) // A check side yields its left operand; the last side always yields, so // the mapping always commits. require.Equal(t, `assign x - source "x = ((a > 2) || 7)" + source + x = ((a > 2) || 7) execute %t0 = @@ -1830,7 +1920,8 @@ s, t, h, g`) `, plans[5].Render(false)) // A check as the last side can fail, so the binding keeps its value. require.Equal(t, `assign n - source "n = ((a > 9) || (a > 1))" + source + n = ((a > 9) || (a > 1)) execute %t0 = @@ -1846,7 +1937,8 @@ s, t, h, g`) // outcome line would have gone, and its value reaches the mapping through // the first's outcome. require.Equal(t, `assign z - source "z = (((a > 0) && 11) || 13)" + source + z = (((a > 0) && 11) || 13) execute %t0 = @@ -1864,7 +1956,8 @@ s, t, h, g`) // Every side may be a last, and the IDs stay dense through each one's own // sides. Where no side yields, a fresh binding holds its zero. require.Equal(t, `assign u - source "u = (((a > 9) && 1) || ((b > 0) && 2))" + source + u = (((a > 9) && 1) || ((b > 0) && 2)) execute %t0 = @@ -1885,7 +1978,8 @@ s, t, h, g`) // The fallback after a side resolves a failed access anywhere in it, a // nested last's final eval included. require.Equal(t, `assign c - source "c = (((1 < 2) && arr[9]) || (-1))" + source + c = (((1 < 2) && arr[9]) || (-1)) execute %t0 = @@ -1903,7 +1997,8 @@ s, t, h, g`) // A check inside a nested last carries the scope its side's position // gives, as the last's final eval does. require.Equal(t, `assign d - source "d = (((arr[9] > 0) && 1) || (-1))" + source + d = (((arr[9] > 0) && 1) || (-1)) execute %t0 = @@ -1921,7 +2016,8 @@ s, t, h, g`) // A check side with a read falls back where the read fails as where the // comparison does, and what it built is released where the fallback ran. require.Equal(t, `assign s - source "s = ((sarr[9] > \"a\") || h)" + source + s = ((sarr[9] > "a") || h) execute %t0 = @@ -1938,7 +2034,8 @@ s, t, h, g`) // transfers name %t2 and %t3; the check before it is only tested, and // what it built is released once it is compared. require.Equal(t, `assign t - source "t = (((MkStr(a) > \"a\") && MkStr(b)) || h)" + source + t = (((MkStr(a) > "a") && MkStr(b)) || h) execute %t0 = @@ -1957,7 +2054,8 @@ s, t, h, g`) // The value after a first takes the ID after every node inside it, a // nested last's own sides included. require.Equal(t, `assign p, q - source "p, q = (((a > 0) && 11) || 13), 5" + source + p, q = (((a > 0) && 11) || 13), 5 execute %t0 = @@ -1978,7 +2076,8 @@ s, t, h, g`) // nested last's own sides included, and the side no fallback follows // skips the outcome from there just as a side of its own would. require.Equal(t, `assign g - source "g = (((a > 0) && sarr[9]) || ((b > 0) && sarr[1]))" + source + g = (((a > 0) && sarr[9]) || ((b > 0) && sarr[1])) execute %t0 = diff --git a/docs/Pluto IR Plan.md b/docs/Pluto IR Plan.md index 3c179f59..22e17973 100644 --- a/docs/Pluto IR Plan.md +++ b/docs/Pluto IR Plan.md @@ -543,7 +543,8 @@ as before, and siblings of a skipped outcome still commit. ```text assign obA, obB - source "obA, obB = obArr[10], 5" + source + obA, obB = obArr[10], 5 execute %t0 = eval I64 obArr[10] [on-oob=skip] @@ -732,15 +733,23 @@ The renderer covers exactly the node kinds the router admits and rejects any other as an ICE, so each step that widens the router adds the renderer and golden for its new node kinds. An eval operand is always one physical line: control characters inside a string literal are escaped (`"line one\nline -two"`). A block-layout array literal — rank-2 rows, a table — is spelled as -in the source with each of its line breaks escaped the same way -(`[\n 1 2\n 3 4\n]`), as the plan's `source` line already shows it -(decided 2026-11-13; matrix rows 2c and 36). `commit` +two"`), and a block-layout array literal — rank-2 rows, a table — is spelled +as in the source with each of its line breaks escaped the same way +(`[\n 1 2\n 3 4\n]`; decided 2026-11-13, matrix rows 2c and 36). + +A plan's `source` follows the opposite rule, since it is the statement as +written rather than an operand: the label stands alone and the statement's own +lines sit one level in, so a block literal reads as its author laid it out +(decided 2026-11-23). Within a line every control character is still escaped, +so a source is never invisible and never breaks the layout; only a line break +becomes a line. A multi-line string literal is the one place the two rules +disagree about what the text holds, and the operand line settles it. `commit` and `advance` carry no mode keyword: both are always simultaneous (§14). ```text assign x - source "x = ((data[i] || other[j]) || (-1))" + source + x = ((data[i] || other[j]) || (-1)) execute %t0 = @@ -764,7 +773,8 @@ transfer (decided 2026-11-20). ```text assign v - source "v = ((n > 2) && 10)" + source + v = ((n > 2) && 10) execute %t0 = @@ -786,7 +796,8 @@ whatever the condition. ```text assign x - source "x = (n > 0) 5" + source + x = (n > 0) 5 execute %t0 = check I64 n > 0 @@ -1408,7 +1419,8 @@ in source order. ```text print - source "\"n: -n\", h, (h ⊕ \"!\")" + source + "n: -n", h, (h ⊕ "!") execute %t0 = eval borrowed Str h @@ -1445,7 +1457,11 @@ the literal as the source spells it, with each line break escaped. ```text assign scores - source "scores = [\n : Name Score\n \"Ada\" 10\n]" + source + scores = [ + : Name Score + "Ada" 10 + ] execute %t0 = eval Table[Name:Str Score:I64] [\n : Name Score\n "Ada" 10\n] @@ -1512,7 +1528,8 @@ freshness. ```text assign skeep - source "skeep = (skeep ⊕ sarr[9])" + source + skeep = (skeep ⊕ sarr[9]) execute %t0 = eval owned Str skeep ⊕ sarr[9] [on-oob=skip] @@ -1596,7 +1613,8 @@ either way. ```text assign s - source "s = (sarr[9] || h)" + source + s = (sarr[9] || h) execute %t0 = @@ -1711,7 +1729,8 @@ that outcome and holds the statement's values in its region. ```text assign s - source "s = (MkStr(n) > \"a\") t" + source + s = (MkStr(n) > "a") t execute %t0 = check owned Str MkStr(n) > "a" @@ -1776,7 +1795,8 @@ before the final one is a comparison, a `check` that is only tested, and the ```text assign t - source "t = ((MkStr(n) > \"a\") && MkStr(x))" + source + t = ((MkStr(n) > "a") && MkStr(x)) execute %t0 = @@ -1843,7 +1863,8 @@ where the comparison holds; where it fails, the binding carries ```text assign s - source "s = (MkStr(a) > \"zzz\")" + source + s = (MkStr(a) > "zzz") execute %t0 = check owned Str MkStr(a) > "zzz" @@ -1904,7 +1925,8 @@ and any other side is an `eval`. ```text assign t - source "t = ((MkStr(a) > \"a\") && MkStr(b)) || h" + source + t = ((MkStr(a) > "a") && MkStr(b)) || h execute %t0 = diff --git a/emit_pir_test.go b/emit_pir_test.go index 8c29bd63..72f5b028 100644 --- a/emit_pir_test.go +++ b/emit_pir_test.go @@ -116,7 +116,8 @@ func TestEmitPIRConcise(t *testing.T) { var out bytes.Buffer require.NoError(t, emitPIR(&out, [][]pir.Plan{emitPIRTestPlans("")}, parsedEmitPIRMode(t, "-emit-pir"))) require.Equal(t, `assign x - source "x = 5" + source + x = 5 execute %t0 = eval I64 5 @@ -125,7 +126,8 @@ func TestEmitPIRConcise(t *testing.T) { x = %t0 assign y - source "y = x" + source + y = x execute %t0 = eval I64 x @@ -155,7 +157,8 @@ func TestEmitPIRFunctionBody(t *testing.T) { var out bytes.Buffer require.NoError(t, emitPIR(&out, bodies, parsedEmitPIRMode(t, "-emit-pir"))) require.Equal(t, `assign x - source "x = 5" + source + x = 5 execute %t0 = eval I64 5 @@ -165,7 +168,8 @@ func TestEmitPIRFunctionBody(t *testing.T) { function I64 = F(I64) assign x - source "x = 5" + source + x = 5 execute %t0 = eval I64 5 @@ -174,7 +178,8 @@ function I64 = F(I64) x = %t0 assign y - source "y = x" + source + y = x execute %t0 = eval I64 x @@ -183,7 +188,8 @@ function I64 = F(I64) y = %t0 print - source "\"y:\", y" + source + "y:", y execute %t0 = eval I64 y @@ -204,7 +210,8 @@ func TestEmitPIRExpanded(t *testing.T) { var out bytes.Buffer require.NoError(t, emitPIR(&out, [][]pir.Plan{{plan}}, parsedEmitPIRMode(t, "-emit-pir=expanded"))) require.Equal(t, `assign y - source "y = x" + source + y = x execute %t0 = eval borrowed Str x diff --git a/pir/pir_test.go b/pir/pir_test.go index 63e7da9e..9452105e 100644 --- a/pir/pir_test.go +++ b/pir/pir_test.go @@ -844,7 +844,8 @@ func TestRenderFirst(t *testing.T) { p := firstPlan() Elaborate(p) want := `assign s - source "s = sarr[9] || h" + source + s = sarr[9] || h execute %t0 = @@ -860,7 +861,8 @@ func TestRenderFirst(t *testing.T) { t.Fatalf("concise render mismatch:\ngot:\n%s\nwant:\n%s", got, want) } want = `assign s - source "s = sarr[9] || h" + source + s = sarr[9] || h execute %t0 = @@ -884,7 +886,8 @@ func TestRenderFirst(t *testing.T) { t.Fatalf("chain plan rejected: %v", err) } want = `assign n, z, m - source "n, z, m = 5, sarr[9] || sarr[8] || sarr[7], 7" + source + n, z, m = 5, sarr[9] || sarr[8] || sarr[7], 7 execute %t0 = eval I64 5 @@ -918,7 +921,8 @@ func TestRenderFirst(t *testing.T) { t.Fatalf("plan with a last for a side rejected: %v", err) } want = `assign t - source "t = MkStr(a) > \"a\" && MkStr(b) || h" + source + t = MkStr(a) > "a" && MkStr(b) || h execute %t0 = @@ -997,7 +1001,8 @@ func TestRenderGate(t *testing.T) { p := gatePlan() Elaborate(p) want := `assign s - source "s = sarr[1] > \"m\" sarr[9]" + source + s = sarr[1] > "m" sarr[9] execute %t0 = check Str sarr[1] > "m" [on-oob=skip] @@ -1011,7 +1016,8 @@ func TestRenderGate(t *testing.T) { t.Fatalf("concise render mismatch:\ngot:\n%s\nwant:\n%s", got, want) } want = `assign s - source "s = sarr[1] > \"m\" sarr[9]" + source + s = sarr[1] > "m" sarr[9] execute %t0 = check owned Str sarr[1] > "m" [on-oob=skip] @@ -1092,7 +1098,8 @@ func TestRenderLast(t *testing.T) { gated := lastGatePlan() Elaborate(gated) want := `assign s - source "s = sarr[1] > \"m\" && t > \"a\" u" + source + s = sarr[1] > "m" && t > "a" u execute %t0 = @@ -1113,7 +1120,8 @@ func TestRenderLast(t *testing.T) { value := lastValuePlan() Elaborate(value) want = `assign s - source "s = sarr[1] > \"m\" && sarr[9]" + source + s = sarr[1] > "m" && sarr[9] execute %t0 = @@ -1163,7 +1171,8 @@ func TestRenderCheck(t *testing.T) { p := checkPlan() Elaborate(p) want := `assign s - source "s = MkStr(n) > \"a\"" + source + s = MkStr(n) > "a" execute %t0 = check Str MkStr(n) > "a" @@ -1175,7 +1184,8 @@ func TestRenderCheck(t *testing.T) { t.Fatalf("concise render mismatch:\ngot:\n%s\nwant:\n%s", got, want) } want = `assign s - source "s = MkStr(n) > \"a\"" + source + s = MkStr(n) > "a" execute %t0 = check owned Str MkStr(n) > "a" @@ -1240,7 +1250,8 @@ func TestValidatePrint(t *testing.T) { func TestRenderPrint(t *testing.T) { p := printPlan() want := `print - source "\"x: -x\", s, Pair(n)" + source + "x: -x", s, Pair(n) execute %t0 = eval Str s @@ -1251,7 +1262,8 @@ func TestRenderPrint(t *testing.T) { t.Fatalf("print render mismatch:\ngot:\n%s\nwant:\n%s", got, want) } wantExpanded := `print - source "\"x: -x\", s, Pair(n)" + source + "x: -x", s, Pair(n) execute %t0 = eval borrowed Str s @@ -1277,7 +1289,8 @@ func TestRenderConcise(t *testing.T) { }, } want := `assign x, _ - source "x, _ = 5, 7" + source + x, _ = 5, 7 execute %t0 = eval I64 5 @@ -1310,7 +1323,8 @@ func TestRenderMultiOutput(t *testing.T) { t.Fatalf("multi-output plan rejected: %v", err) } want := `assign a, b - source "a, b = Pair(x)" + source + a, b = Pair(x) execute %t0 = eval I64, Str Pair(x) @@ -1323,7 +1337,8 @@ func TestRenderMultiOutput(t *testing.T) { t.Fatalf("multi-output render mismatch:\ngot:\n%s\nwant:\n%s", got, want) } wantExpanded := `assign a, b - source "a, b = Pair(x)" + source + a, b = Pair(x) execute %t0 = eval I64, owned Str Pair(x) @@ -1348,7 +1363,8 @@ func TestRenderFunctionOutput(t *testing.T) { } want := ` assign res - source "res = a ⊕ b" + source + res = a ⊕ b execute %t0 = eval Str a ⊕ b @@ -1360,7 +1376,8 @@ func TestRenderFunctionOutput(t *testing.T) { t.Fatalf("function output render mismatch:\ngot:\n%s\nwant:\n%s", got, want) } wantExpanded := ` assign res - source "res = a ⊕ b" + source + res = a ⊕ b execute %t0 = eval owned Str a ⊕ b @@ -1414,7 +1431,8 @@ func TestRenderExpanded(t *testing.T) { Elaborate(p) got := p.Render(true) want := `assign a, b - source "a, b = b, a" + source + a, b = b, a execute %t0 = eval I64 b @@ -1434,7 +1452,8 @@ func TestRenderExpanded(t *testing.T) { // release, and the replaced value's release after the mappings. func TestRenderExpandedOwnership(t *testing.T) { want := `assign a, b - source "a, b = b, a" + source + a, b = b, a execute %t0 = eval borrowed Str b @@ -1450,7 +1469,8 @@ func TestRenderExpandedOwnership(t *testing.T) { t.Fatalf("heap swap render mismatch:\ngot:\n%s\nwant:\n%s", got, want) } want = `assign x, _ - source "x, _ = x ⊕ \"!\", \"a\" ⊕ \"b\"" + source + x, _ = x ⊕ "!", "a" ⊕ "b" execute %t0 = eval owned Str x ⊕ "!" @@ -1469,7 +1489,8 @@ func TestRenderExpandedOwnership(t *testing.T) { } // The concise view omits every derived decision. want = `assign x, _ - source "x, _ = x ⊕ \"!\", \"a\" ⊕ \"b\"" + source + x, _ = x ⊕ "!", "a" ⊕ "b" execute %t0 = eval Str x ⊕ "!" @@ -1491,7 +1512,8 @@ func TestRenderSkip(t *testing.T) { p := skipPlan() Elaborate(p) want := `assign kept, fresh, _ - source "kept, fresh, _ = sarr[9], sarr[0], sarr[1]" + source + kept, fresh, _ = sarr[9], sarr[0], sarr[1] execute %t0 = eval Str sarr[9] [on-oob=skip] @@ -1507,7 +1529,8 @@ func TestRenderSkip(t *testing.T) { t.Fatalf("concise render mismatch:\ngot:\n%s\nwant:\n%s", got, want) } want = `assign kept, fresh, _ - source "kept, fresh, _ = sarr[9], sarr[0], sarr[1]" + source + kept, fresh, _ = sarr[9], sarr[0], sarr[1] execute %t0 = eval owned Str sarr[9] [on-oob=skip] @@ -1548,7 +1571,7 @@ func TestRenderEscapesControls(t *testing.T) { evalAt(p, 0).Slots[0].Type = testType("Str") p.Commit = p.Commit[:1] got := p.Render(false) - if !strings.Contains(got, " "+tc.want+"\n") || strings.Count(got, "\n") != 8 { + if !strings.Contains(got, " "+tc.want+"\n") || strings.Count(got, "\n") != 9 { t.Fatalf("render mismatch:\n%s", got) } } diff --git a/pir/print.go b/pir/print.go index 4f260d05..4a4b06cb 100644 --- a/pir/print.go +++ b/pir/print.go @@ -3,7 +3,6 @@ package pir import ( "fmt" "slices" - "strconv" "strings" "unicode" @@ -98,10 +97,20 @@ func writeNodes(b *strings.Builder, indent string, nodes []Node, expanded bool) } // writeHead writes what every plan opens with: its header, its source, and -// the line that opens its execute region. +// the line that opens its execute region. The source prints as the +// statement's own lines, one level in, so a literal that spans lines reads as +// it was written, and every other control character is still escaped. A +// node's operand stays one line, line breaks escaped with it (plan §12). func writeHead(b *strings.Builder, head Head) { fmt.Fprintf(b, "%s\n", head.Label) - fmt.Fprintf(b, " source %s\n", strconv.Quote(head.Source)) + b.WriteString(" source\n") + for _, line := range strings.Split(head.Source, "\n") { + if line == "" { + b.WriteString("\n") + continue + } + fmt.Fprintf(b, " %s\n", escapeControls(line)) + } b.WriteString("\n execute\n") } From a3d5aafe6a6c8e3b598ad9138a1df942feebad53 Mon Sep 17 00:00:00 2001 From: Tejas Date: Mon, 23 Nov 2026 16:08:02 +0530 Subject: [PATCH 02/39] fix(pir): let no two statements render alike MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two reviews found three ways the text view hid a difference, each reproduced through -emit-pir. A line terminator read differently depending on how the file spelled it. writeHead split on LF alone, so a CRLF left a stray \r at the end of the row it broke and a lone CR never broke at all; worse, a lone CR and the escape \r both rendered \r in the operand while the first runs as 0a and the second as 0d. Every terminator the language counts as one — LF, CRLF and CR (README) — now reads as one, so a terminator breaks a source line and prints \n in an operand, and only an escape in the source prints \r. An invisible rune lost its spelling. escapeControls escaped controls and the line and paragraph separators, which left the format characters raw: a zero-width space between two letters rendered as nothing at all, in the source since this branch and in an operand all along. It now spells out every rune Unicode calls unprintable, with \U for one past the BMP, where the old \u truncated. A line of spaces lost four columns in a function body. indent skipped it as blank, since TrimSpace empties it, so a multi-line string's middle line sat at nine columns where the margin alone is twelve. Only an empty line is skipped now, which is what separates a plan's sections. TestRenderSource covers what writeHead renders: a source of several lines, an empty line, a line of spaces and a line of one tab, controls, invisibles, a raw quote and backslash, CR and CRLF, and each of those a function body indents. TestRenderEscapesControls gains the operand side of the terminator and invisible rules. Four mutants, one per fix, each kill named subtests. Machine code is untouched: all 89 fixture executables still have an identical __text, and with every source section elided the plan text over master's fixtures is still byte-identical, so no operand in the fixtures moved either. Co-Authored-By: Claude Opus 5 --- pir/pir_test.go | 54 ++++++++++++++++++++++++++++++++++++++++++++++--- pir/print.go | 44 +++++++++++++++++++++++++++------------- 2 files changed, 81 insertions(+), 17 deletions(-) diff --git a/pir/pir_test.go b/pir/pir_test.go index 9452105e..28bc0d24 100644 --- a/pir/pir_test.go +++ b/pir/pir_test.go @@ -1551,18 +1551,66 @@ func TestRenderSkip(t *testing.T) { } } +// Plan §12: a plan's source prints as the ast's own lines, one level in, so a +// literal that spans lines reads as it is laid out. Every character a reader +// could not otherwise see is escaped, a line of spaces keeps its own +// indentation at either level, and only an empty line stays bare, since those +// separate a plan's sections. +func TestRenderSource(t *testing.T) { + cases := []struct { + name string + source string + fn string + want string + }{ + {"OneLine", "a, b = b, a", "", " a, b = b, a"}, + {"Lines", "m = [\n 1 2\n 3 4\n]", "", " m = [\n 1 2\n 3 4\n ]"}, + {"EmptyLine", "s = \"a\n\nb\"", "", " s = \"a\n\n b\""}, + {"SpaceOnlyLine", "s = \"a\n \nb\"", "", " s = \"a\n \n b\""}, + {"TabOnlyLine", "s = \"a\n\t\nb\"", "", " s = \"a\n \\t\n b\""}, + {"Controls", "s = \"a\x01b\x7fc\td\"", "", " s = \"a\\x01b\\x7fc\\td\""}, + {"Invisible", "s = \"x\u200by\"", "", " s = \"x\\u200by\""}, + {"QuoteAndBackslash", `s = "a\"b\\c"`, "", " s = \"a\\\"b\\\\c\""}, + {"CRLFIsOneBreak", "s = \"a\r\nb\"", "", " s = \"a\n b\""}, + {"CRIsOneBreak", "s = \"a\rb\"", "", " s = \"a\n b\""}, + {"LinesInFunctionBody", "m = [\n 1 2\n]", "I64 = F(I64)", " m = [\n 1 2\n ]"}, + {"EmptyLineInFunctionBody", "s = \"a\n\nb\"", "I64 = F(I64)", " s = \"a\n\n b\""}, + {"SpaceOnlyLineInFunctionBody", "s = \"a\n \nb\"", "I64 = F(I64)", " s = \"a\n \n b\""}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + p := swapPlan() + p.Source = tc.source + p.Func = tc.fn + head := "assign a, b\n source\n" + if tc.fn != "" { + head = " assign a, b\n source\n" + } + got := p.Render(false) + if want := head + tc.want + "\n\n"; !strings.HasPrefix(got, want) { + t.Fatalf("source mismatch:\ngot:\n%q\nwant prefix:\n%q", got, want) + } + }) + } +} + // Plan §12: control characters and Unicode line breaks inside string // literals never break the one-operation-per-line format, at the root or -// nested under an operator; ordinary non-ASCII stays raw. +// nested under an operator; ordinary non-ASCII stays raw. A terminator the +// file spells CR is one line break, so it renders as the escape a source +// asks for with `\r` does not. func TestRenderEscapesControls(t *testing.T) { multi := strLit("a\nb\tc\rd\x01e\x7f") cases := []struct { expr ast.Expression want string }{ - {multi, `%t0 = eval Str "a\nb\tc\rd\x01e\x7f"`}, - {concat(multi, strLit("z")), `%t0 = eval Str "a\nb\tc\rd\x01e\x7f" ⊕ "z"`}, + {multi, `%t0 = eval Str "a\nb\tc\nd\x01e\x7f"`}, + {concat(multi, strLit("z")), `%t0 = eval Str "a\nb\tc\nd\x01e\x7f" ⊕ "z"`}, + {strLit("a\r\nb"), `%t0 = eval Str "a\nb"`}, + {strLit(`a\rb`), `%t0 = eval Str "a\rb"`}, {strLit("π\u0085x\u2028y\u2029z\u009f"), `%t0 = eval Str "π\u0085x\u2028y\u2029z\u009f"`}, + {strLit("x\u200by\U000e0001z"), `%t0 = eval Str "x\u200by\U000e0001z"`}, } for _, tc := range cases { p := swapPlan() diff --git a/pir/print.go b/pir/print.go index 4a4b06cb..6cd770b8 100644 --- a/pir/print.go +++ b/pir/print.go @@ -99,12 +99,13 @@ func writeNodes(b *strings.Builder, indent string, nodes []Node, expanded bool) // writeHead writes what every plan opens with: its header, its source, and // the line that opens its execute region. The source prints as the // statement's own lines, one level in, so a literal that spans lines reads as -// it was written, and every other control character is still escaped. A -// node's operand stays one line, line breaks escaped with it (plan §12). +// the ast spells it, and every other character a reader cannot see is still +// escaped. A node's operand stays one line, line breaks escaped with it +// (plan §12). func writeHead(b *strings.Builder, head Head) { fmt.Fprintf(b, "%s\n", head.Label) b.WriteString(" source\n") - for _, line := range strings.Split(head.Source, "\n") { + for _, line := range strings.Split(logicalNewlines(head.Source), "\n") { if line == "" { b.WriteString("\n") continue @@ -177,11 +178,13 @@ func FuncHeader(fn string) string { return "function " + fn + "\n" } -// indent moves every non-blank line one level in. +// indent moves every line one level in but the empty ones, which separate a +// plan's sections: a line of spaces belongs to a multi-line source and keeps +// its own indentation. func indent(text string) string { lines := strings.SplitAfter(text, "\n") for i, line := range lines { - if strings.TrimSpace(line) != "" { + if line != "" && line != "\n" { lines[i] = " " + line } } @@ -203,24 +206,37 @@ func renderPayload(expr ast.Expression) string { return escapeControls(s) } -// escapeControls keeps an operand on one physical line: C0 and C1 controls -// and the Unicode line and paragraph separators are escaped. +// logicalNewlines rewrites every line terminator Pluto counts as one — LF, +// CRLF and CR alike (README, "Source files are UTF-8") — to LF, so a +// terminator reads the same however a file spells it and never collides with +// the `\r` an escape in the source asks for. +func logicalNewlines(s string) string { + if !strings.ContainsRune(s, '\r') { + return s + } + return strings.ReplaceAll(strings.ReplaceAll(s, "\r\n", "\n"), "\r", "\n") +} + +// escapeControls spells out what a reader would not otherwise see, so that an +// operand stays on one physical line, a source line keeps its own, and no two +// statements render alike: a line terminator, a tab, and every rune Unicode +// calls unprintable, the format and separator characters among them. func escapeControls(s string) string { var b strings.Builder - for _, r := range s { + for _, r := range logicalNewlines(s) { switch { case r == '\n': b.WriteString(`\n`) case r == '\t': b.WriteString(`\t`) - case r == '\r': - b.WriteString(`\r`) - case r < 0x80 && unicode.IsControl(r): + case unicode.IsPrint(r): + b.WriteRune(r) + case r < 0x80: fmt.Fprintf(&b, `\x%02x`, r) - case unicode.IsControl(r) || unicode.Is(unicode.Zl, r) || unicode.Is(unicode.Zp, r): - fmt.Fprintf(&b, `\u%04x`, r) + case r > 0xffff: + fmt.Fprintf(&b, `\U%08x`, r) default: - b.WriteRune(r) + fmt.Fprintf(&b, `\u%04x`, r) } } return b.String() From b0fbf4583bc8706cb2817d91ce742bf8beb0ff15 Mon Sep 17 00:00:00 2001 From: Tejas Date: Mon, 23 Nov 2026 16:08:08 +0530 Subject: [PATCH 03/39] docs(pir): say a plan's source is the ast's spelling MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit §12 called the source the statement "as written", which a review noted it is not: the compiler renders stmt.String(), so an operator root carries the pair it wraps itself in (`d = (Twice(d) + 1)`) and a block literal's rows carry the ast's indentation rather than the file's. The rule now says so, states that LF, CRLF and CR each count as one terminator, and names what a line escapes. The sentence about `commit` and `advance`, left tacked onto the end when this paragraph split in two, goes back to its own. Co-Authored-By: Claude Opus 5 --- docs/Pluto IR Plan.md | 26 ++++++++++++++++++-------- 1 file changed, 18 insertions(+), 8 deletions(-) diff --git a/docs/Pluto IR Plan.md b/docs/Pluto IR Plan.md index 22e17973..29fab8fe 100644 --- a/docs/Pluto IR Plan.md +++ b/docs/Pluto IR Plan.md @@ -737,14 +737,24 @@ two"`), and a block-layout array literal — rank-2 rows, a table — is spelled as in the source with each of its line breaks escaped the same way (`[\n 1 2\n 3 4\n]`; decided 2026-11-13, matrix rows 2c and 36). -A plan's `source` follows the opposite rule, since it is the statement as -written rather than an operand: the label stands alone and the statement's own -lines sit one level in, so a block literal reads as its author laid it out -(decided 2026-11-23). Within a line every control character is still escaped, -so a source is never invisible and never breaks the layout; only a line break -becomes a line. A multi-line string literal is the one place the two rules -disagree about what the text holds, and the operand line settles it. `commit` -and `advance` carry no mode keyword: both are always simultaneous (§14). +A plan's `source` follows the opposite rule, since it is the whole statement +rather than an operand: the label stands alone and the statement's own lines +sit one level in, so a block literal reads as it is laid out (decided +2026-11-23). What it renders is the ast's spelling of the statement, not the +file's bytes, so an operator root carries the pair it wraps itself in +(`d = (Twice(d) + 1)`) and a block literal's rows carry the ast's own +indentation. Within a line, everything a reader could not otherwise see is +escaped — a tab, a control, and every rune Unicode calls unprintable, the +format and separator characters among them — so no two statements render +alike and a source never breaks the layout. Only a line terminator becomes a +line, and LF, CRLF and CR all count as one (README), so a terminator reads the +same however a file spells it and never collides with the `\r` a source asks +for by escape. A multi-line string literal is the one place the two rules +disagree about what the text holds: the source shifts its continuation to the +section's indent, and the operand beside it is exact. + +`commit` and `advance` carry no mode keyword: both are always simultaneous +(§14). ```text assign x From 18eabfa8a61aaffa5a67538a949ad752cf773229 Mon Sep 17 00:00:00 2001 From: Tejas Date: Mon, 23 Nov 2026 17:38:38 +0530 Subject: [PATCH 04/39] docs(pir): claim only what the escaping rules give MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A review read §12's "no two statements render alike" literally and found the counter-example: a physical tab and a `\t` escape render the same `\t`, and so they should, since both hold one tab and emit 09. The same goes for a physical line break and a `\n` escape, which both emit 0a. What the rules rule out is two statements that DIFFER rendering alike, which is exactly what a CR used to do against `\r` — one emits 0a, the other 0d. §12 now says that, with the tab as the named harmless case. a3d5aaf's subject overclaims the same way; it stays as it was pushed. logicalNewlines cites lexer.LogicalRune rather than the README, since the lexer is what it has to agree with: it reads CRLF and a lone CR as one `\n` and nothing else, which is the set this mirrors. Co-Authored-By: Claude Opus 5 --- docs/Pluto IR Plan.md | 6 ++++-- pir/print.go | 6 +++--- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/docs/Pluto IR Plan.md b/docs/Pluto IR Plan.md index 29fab8fe..a8ca7462 100644 --- a/docs/Pluto IR Plan.md +++ b/docs/Pluto IR Plan.md @@ -745,8 +745,10 @@ file's bytes, so an operator root carries the pair it wraps itself in (`d = (Twice(d) + 1)`) and a block literal's rows carry the ast's own indentation. Within a line, everything a reader could not otherwise see is escaped — a tab, a control, and every rune Unicode calls unprintable, the -format and separator characters among them — so no two statements render -alike and a source never breaks the layout. Only a line terminator becomes a +format and separator characters among them — so a source never breaks the +layout. Two statements still render alike where they hold the same text, a +physical tab and a `\t` escape among them; what these rules rule out is two +statements that differ. Only a line terminator becomes a line, and LF, CRLF and CR all count as one (README), so a terminator reads the same however a file spells it and never collides with the `\r` a source asks for by escape. A multi-line string literal is the one place the two rules diff --git a/pir/print.go b/pir/print.go index 6cd770b8..f03f8916 100644 --- a/pir/print.go +++ b/pir/print.go @@ -207,9 +207,9 @@ func renderPayload(expr ast.Expression) string { } // logicalNewlines rewrites every line terminator Pluto counts as one — LF, -// CRLF and CR alike (README, "Source files are UTF-8") — to LF, so a -// terminator reads the same however a file spells it and never collides with -// the `\r` an escape in the source asks for. +// CRLF and CR alike, as lexer.LogicalRune reads them — to LF, so a terminator +// reads the same however a file spells it and never collides with the `\r` an +// escape in the source asks for. func logicalNewlines(s string) string { if !strings.ContainsRune(s, '\r') { return s From 64058e0e143ddf7b9d46bb4847f6d3f6e478d374 Mon Sep 17 00:00:00 2001 From: Tejas Date: Mon, 23 Nov 2026 18:09:17 +0530 Subject: [PATCH 05/39] feat(parser): record the source a statement is spelled with MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A plan quoted the ast's rendering of its statement, which spells out its own nesting: every infix and prefix expression parenthesises itself, so `b = a + 2 * 3` read `b = (a + (2 * 3))` and `5a` read `(5 ⋅ a)`. Stripping those at the top only moves the problem, since the ast adds them for a reason — the parser's precedence oracle is exactly that spelling. So a statement now carries the text its file gives it. The lexer keeps the input's lines and notes where each line's comment starts, and Text quotes a span: the lines it covers, each cut before a comment that line ends with, dedented to the line it starts on so a caller can place them at its own level. Every terminator the language counts as one ends one line, as LogicalRune reads them. The parser fills Src from the token a statement started at to the one it ended on, for a let and for a print. Nothing reads Src yet. The ast's own String stays as it was, so the precedence oracle keeps the spelling it asserts. Co-Authored-By: Claude Opus 5 --- ast/ast.go | 2 ++ lexer/lexer.go | 52 +++++++++++++++++++++++++++ lexer/lexer_test.go | 48 +++++++++++++++++++++++++ parser/parser.go | 17 +++++++++ parser/scriptparser_test.go | 71 +++++++++++++++++++++++++++++++++++++ 5 files changed, 190 insertions(+) diff --git a/ast/ast.go b/ast/ast.go index 3a7d7574..59885fbc 100644 --- a/ast/ast.go +++ b/ast/ast.go @@ -145,6 +145,7 @@ type LetStatement struct { Name []*Identifier Value []Expression Condition []Expression + Src string // the source the file spells it with; String() where a caller built it } func (ls *LetStatement) statementNode() {} @@ -175,6 +176,7 @@ func (ls *LetStatement) String() string { type PrintStatement struct { Token token.Token // the first token of the expression Expression *CallExpression + Src string // the source the file spells it with; String() where a caller built it } func (ps *PrintStatement) statementNode() {} diff --git a/lexer/lexer.go b/lexer/lexer.go index 6f86b6ca..505d7f4f 100644 --- a/lexer/lexer.go +++ b/lexer/lexer.go @@ -18,6 +18,9 @@ type Lexer struct { lineOffset int // line number column int // column number in the line + lines []string // the input's physical lines, read on demand + comments map[int]int // the column a line's comment starts at, by line + blocks []block // the open indented blocks; innermost last pending queue // tokens decided but not yet returned last token.TokenType // the last token returned, NEWLINE at the start; a line ending in a comma or '=' continues @@ -92,6 +95,53 @@ func (l *Lexer) createToken(tokenType token.TokenType, literal string, hadSpace return tok } +// noteComment records where the comment on the line being read starts, so +// that quoting a statement can stop before it. +func (l *Lexer) noteComment() { + if l.comments == nil { + l.comments = make(map[int]int) + } + l.comments[l.lineOffset] = l.column +} + +// Lines returns the source as its physical lines, each terminator the +// language counts as one — LF, CRLF and CR alike, as LogicalRune reads them — +// ending exactly one line. +func (l *Lexer) Lines() []string { + if l.lines == nil { + text := strings.ReplaceAll(strings.ReplaceAll(string(l.input), "\r\n", "\n"), "\r", "\n") + l.lines = strings.Split(text, "\n") + } + return l.lines +} + +// Text is the source a statement is spelled with: the lines it spans, each +// cut before any comment that line ends with, dedented by the indentation of +// the line it starts on, and with trailing space dropped. Lines and columns +// are the ones a token carries, counted from one. It is empty where the span +// names no line of this input. +func (l *Lexer) Text(startLine, startColumn, endLine int) string { + lines := l.Lines() + if startLine < 1 || startLine > endLine || endLine > len(lines) { + return "" + } + + spelled := make([]string, 0, endLine-startLine+1) + for n := startLine; n <= endLine; n++ { + runes := []rune(lines[n-1]) + if column, commented := l.comments[n]; commented { + runes = runes[:min(column-1, len(runes))] + } + if dedent := startColumn - 1; dedent < len(runes) { + runes = runes[dedent:] + } else { + runes = nil + } + spelled = append(spelled, strings.TrimRight(string(runes), " \t")) + } + return strings.Join(spelled, "\n") +} + // tokenAt makes a token at column on the line being read. func (l *Lexer) tokenAt(tokenType token.TokenType, literal string, column int) token.Token { return token.Token{ @@ -292,6 +342,7 @@ func (l *Lexer) lex() (token.Token, *token.CompileError) { hadSpace := l.skipWhitespace() if l.curr == '#' { + l.noteComment() l.skipComment() } @@ -416,6 +467,7 @@ func (l *Lexer) nextLine() (column int, first rune, tab int) { case '\n': // a blank line l.skipWhitespace() case '#': // a comment line + l.noteComment() l.skipComment() default: return column, first, tab diff --git a/lexer/lexer_test.go b/lexer/lexer_test.go index 4bf58674..b53023e9 100644 --- a/lexer/lexer_test.go +++ b/lexer/lexer_test.go @@ -1418,3 +1418,51 @@ func TestDecodeStringEscapePhysicalBreak(t *testing.T) { } } } + +// Text quotes a statement as its file spells it: lines dedented to the one it +// starts on, each cut before a comment, with LF, CRLF and CR all ending one +// line. A span naming no line of the input is empty. +func TestText(t *testing.T) { + const script = "a = 1 # one\nm = [\n # a row\n 2 3\n]\n" + const body = "r = G(x)\n m = [\n 2 3\n ]\n" + cases := []struct { + name string + src string + startLine, startColumn, endLine int + want string + }{ + {"OneLineCutsItsComment", script, 1, 1, 1, "a = 1"}, + {"LinesKeepTheirShape", script, 2, 1, 5, "m = [\n\n 2 3\n]"}, + {"DedentedToItsFirstLine", body, 2, 5, 4, "m = [\n 2 3\n]"}, + {"BeforeTheInput", script, 0, 1, 1, ""}, + {"PastTheInput", script, 1, 1, 99, ""}, + {"Backwards", script, 3, 1, 2, ""}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + l := New("TestText", tc.src) + for { + tok, _ := l.NextToken() + if tok.Type == token.EOF { + break + } + } + if got := l.Text(tc.startLine, tc.startColumn, tc.endLine); got != tc.want { + t.Fatalf("Text(%d, %d, %d) = %q, want %q", tc.startLine, tc.startColumn, tc.endLine, got, tc.want) + } + }) + } +} + +// Text reads a terminator the same however the file spells it, as the lexer +// itself does. +func TestTextLineEndings(t *testing.T) { + for name, src := range map[string]string{"LF": "a = 1\nb = 2\n", "CRLF": "a = 1\r\nb = 2\r\n", "CR": "a = 1\rb = 2\r"} { + t.Run(name, func(t *testing.T) { + l := New("TestTextLineEndings", src) + if got, want := l.Text(1, 1, 2), "a = 1\nb = 2"; got != want { + t.Fatalf("Text = %q, want %q", got, want) + } + }) + } +} diff --git a/parser/parser.go b/parser/parser.go index 9bb505f4..d206759f 100644 --- a/parser/parser.go +++ b/parser/parser.go @@ -98,6 +98,7 @@ type StmtParser struct { curToken token.Token peekToken token.Token + stmtStart token.Token // the first token of the statement being parsed savedTokens []token.Token // FIFO queue of synthetic tokens from operator splits or inserting a * in something like 9x prefixParseFns map[string]prefixParseFn @@ -409,6 +410,7 @@ func (p *StmtParser) ParseProgram() *ast.Program { program.Statements = []ast.Statement{} for !p.curTokenIs(token.EOF) { if stmt := p.parseStatement(); stmt != nil { + p.spell(stmt) program.Statements = append(program.Statements, stmt) } else { p.skipLine() @@ -419,11 +421,25 @@ func (p *StmtParser) ParseProgram() *ast.Program { return program } +// spell gives stmt the source its file spells it with, from the token the +// statement started at to the one it ended on. A plan quotes that rather than +// the ast's own rendering, so what a reader sees is what they wrote. +func (p *StmtParser) spell(stmt ast.Statement) { + src := p.l.Text(p.stmtStart.Line, p.stmtStart.Column, p.curToken.Line) + switch s := stmt.(type) { + case *ast.LetStatement: + s.Src = src + case *ast.PrintStatement: + s.Src = src + } +} + func (p *StmtParser) parseStatement() ast.Statement { if p.skipIndented() { return nil } firstToken := p.curToken + p.stmtStart = firstToken p.blankIdents = nil // reset for new statement expList := p.parseExpList(prefixSplitNone, 0) // An expression that failed to parse is nil and has already reported its @@ -1675,6 +1691,7 @@ func (p *StmtParser) parseBlockStatement() *ast.BlockStatement { for !p.curTokenIs(token.DEINDENT) && !p.curTokenIs(token.EOF) { if stmt := p.parseStatement(); stmt != nil { + p.spell(stmt) block.Statements = append(block.Statements, stmt) } else { p.skipLine() diff --git a/parser/scriptparser_test.go b/parser/scriptparser_test.go index 05361e35..262f2e70 100644 --- a/parser/scriptparser_test.go +++ b/parser/scriptparser_test.go @@ -51,6 +51,77 @@ func TestAssign(t *testing.T) { } } +// Plan §12: a statement carries the source its file spells it with, so a +// plan quotes what its author wrote rather than the ast's own rendering: the +// parens the ast adds are absent, an implicit multiplication reads as it was +// typed, a comment the line ends with is cut, and a statement of several +// lines keeps its own shape dedented to its first line. +func TestStatementSpelling(t *testing.T) { + const script = `b = a + 2 * 3 +n = -a +imp = 5a +f = -8 >> 1 # arithmetic right shift +m = [ + 1 2 + 3 4 +] +long = + a + 1 +"out: -b -n" +` + want := []string{ + "b = a + 2 * 3", + "n = -a", + "imp = 5a", + "f = -8 >> 1", + "m = [\n 1 2\n 3 4\n]", + "long =\n a + 1", + `"out: -b -n"`, + } + + l := lexer.New("TestStatementSpelling", script) + sp := NewScriptParser(l) + program := sp.Parse() + require.Empty(t, sp.Errors(), "unexpected parse errors: %v", sp.Errors()) + require.Len(t, program.Statements, len(want)) + + for i, stmt := range program.Statements { + switch s := stmt.(type) { + case *ast.LetStatement: + require.Equal(t, want[i], s.Src, "statement %d", i) + case *ast.PrintStatement: + require.Equal(t, want[i], s.Src, "statement %d", i) + default: + t.Fatalf("statement %d is %T", i, stmt) + } + } +} + +// Plan §12: a statement inside a function body is spelled dedented to its own +// first line, so a plan can place it at its own level. +func TestStatementSpellingInBody(t *testing.T) { + const code = `r = G(x) + t = x * 2 # doubled + r = t + 1 +` + l := lexer.New("TestStatementSpellingInBody", code) + cp := NewCodeParser(l) + parsed := cp.Parse() + require.Empty(t, cp.Errors(), "unexpected parse errors: %v", cp.Errors()) + + var spelled []string + for _, stmt := range parsed.Statements { + fn, isFunc := stmt.(*ast.FuncStatement) + if !isFunc { + continue + } + for _, inner := range fn.Body.Statements { + spelled = append(spelled, inner.(*ast.LetStatement).Src) + } + } + require.Equal(t, []string{"t = x * 2", "r = t + 1"}, spelled) +} + func TestInvalidAssignment(t *testing.T) { tests := []struct { name string From 3b73aef4b4d80cd4910c4dfaad655c49f10758ed Mon Sep 17 00:00:00 2001 From: Tejas Date: Mon, 23 Nov 2026 18:09:22 +0530 Subject: [PATCH 06/39] feat(pir): quote a plan's source from the file MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A plan's source is now the text the file spells the statement with, so the parens it shows are the ones its author wrote: b = a + 2 * 3 was b = (a + (2 * 3)) n = -a was n = (-a) h1 = "foo" ⊕ "bar" was h1 = ("foo" ⊕ "bar") imp = 5a was imp = (5 ⋅ a) hc = a > 2 7 was hc = (a > 2) 7 f = -8 >> 1 was f = (-8 >> 1), the line's comment cut A statement no file spells — one a caller built — falls back to the ast's rendering, which is what pir's own hand-built plans carry. The operand lines are unchanged: a node is one line, and what it shows is the ast's spelling, parens and `⋅` included. So a reader sees what they wrote beside what the planner made of it, which is the split §12 already draws. Every one of the 52 golden source blocks was checked to differ from its old text only inside the source section before it was replaced. All 89 fixture executables have an identical __text, and with every source section elided the plan text over master's fixtures is byte-identical. Co-Authored-By: Claude Opus 5 --- compiler/pir.go | 13 ++++- compiler/pir_test.go | 117 +++++++++++++++++++++++------------------- docs/Pluto IR Plan.md | 30 ++++++----- 3 files changed, 92 insertions(+), 68 deletions(-) diff --git a/compiler/pir.go b/compiler/pir.go index 89ebaa19..7d817620 100644 --- a/compiler/pir.go +++ b/compiler/pir.go @@ -271,6 +271,15 @@ func (c *Compiler) planExprEligible(expr ast.Expression, reads bool) bool { return true } +// spelling is the source a plan quotes: what the file gave the statement, +// falling back to the ast's own rendering for a statement no file spells. +func spelling(src string, stmt ast.Statement) string { + if src != "" { + return src + } + return stmt.String() +} + // planOOBScope gives a node's index reads their scope (plan §9): a failed // read runs the fallback that follows its side of a first, and skips the // outcome otherwise. The router admits a read only in those two places. @@ -380,7 +389,7 @@ func (c *Compiler) buildLetPlan(stmt *ast.LetStatement, fn string) *pir.AssignPl nameParts[i] = ident.Value } plan := &pir.AssignPlan{ - Head: pir.Head{Label: "assign " + strings.Join(nameParts, ", "), Func: fn, Source: stmt.String()}, + Head: pir.Head{Label: "assign " + strings.Join(nameParts, ", "), Func: fn, Source: spelling(stmt.Src, stmt)}, Commit: make([]pir.Mapping, 0, len(stmt.Name)), } @@ -529,7 +538,7 @@ func (c *Compiler) mapNextTarget(plan *pir.AssignPlan, stmt *ast.LetStatement, o // string literal as itself, since print formats it in place, and any other // argument as the outcome of its eval. func (c *Compiler) buildPrintPlan(stmt *ast.PrintStatement, fn string) *pir.PrintPlan { - plan := &pir.PrintPlan{Head: pir.Head{Label: "print", Func: fn, Source: stmt.String()}} + plan := &pir.PrintPlan{Head: pir.Head{Label: "print", Func: fn, Source: spelling(stmt.Src, stmt)}} for _, expr := range stmt.Expression.Arguments { if lit, isLit := expr.(*ast.StringLiteral); isLit { plan.Args = append(plan.Args, pir.PrintArg{Literal: lit}) diff --git a/compiler/pir_test.go b/compiler/pir_test.go index 8ce44a75..4ad791ab 100644 --- a/compiler/pir_test.go +++ b/compiler/pir_test.go @@ -9,6 +9,7 @@ import ( "github.com/stretchr/testify/require" "github.com/thiremani/pluto/ast" "github.com/thiremani/pluto/pir" + "github.com/thiremani/pluto/token" "tinygo.org/x/go-llvm" ) @@ -96,7 +97,7 @@ s`) require.Equal(t, `assign b source - b = (a + (2 * 3)) + b = a + 2 * 3 execute %t0 = eval I64 a + (2 * 3) @@ -412,7 +413,7 @@ func TestPlanGoldenPrefix(t *testing.T) { require.Equal(t, []string{"assign a", "assign n"}, planLabels(plans)) require.Equal(t, `assign n source - n = (-a) + n = -a execute %t0 = eval I64 -a @@ -485,7 +486,7 @@ h1, h2`) require.Equal(t, []string{"assign h1", "assign h2", "assign h1, h2"}, planLabels(plans)) require.Equal(t, `assign h1 source - h1 = ("foo" ⊕ "bar") + h1 = "foo" ⊕ "bar" execute %t0 = eval owned Str "foo" ⊕ "bar" @@ -551,7 +552,7 @@ x, y`) require.Equal(t, []string{"assign x", "assign x", "assign _", "assign _", "assign y", "assign x, y"}, planLabels(plans)) require.Equal(t, `assign x source - x = (x ⊕ "!") + x = x ⊕ "!" execute %t0 = eval owned Str x ⊕ "!" @@ -562,7 +563,7 @@ x, y`) `, plans[1].Render(true)) require.Equal(t, `assign _ source - _ = (x ⊕ "?") + _ = x ⊕ "?" execute %t0 = eval owned Str x ⊕ "?" @@ -583,7 +584,7 @@ x, y`) `, plans[3].Render(true)) require.Equal(t, `assign x, y source - x, y = (y ⊕ "!"), x + x, y = y ⊕ "!", x execute %t0 = eval owned Str y ⊕ "!" @@ -787,7 +788,7 @@ copy, other, text`) require.Equal(t, []string{"assign text", "assign text, other", "assign copy", "assign other"}, planLabels(plans)) require.Equal(t, `assign text, other source - text, other = (text ⊕ "!"), text + text, other = text ⊕ "!", text execute %t0 = eval owned Str text ⊕ "!" @@ -822,6 +823,18 @@ copy, other, text`) require.True(t, plans[3].Commit[0].Target.HoldsHeap) } +// Plan §12: a plan quotes the source its file spells the statement with, and +// falls back to the ast's rendering for a statement no file spells. +func TestPlanSourceFallsBackToTheAst(t *testing.T) { + stmt := &ast.LetStatement{ + Token: token.Token{Type: token.ASSIGN, Literal: "="}, + Name: []*ast.Identifier{{Token: token.Token{Type: token.IDENT, Literal: "x"}, Value: "x"}}, + Value: []ast.Expression{&ast.IntegerLiteral{Token: token.Token{Type: token.INT, Literal: "5"}, Value: 5}}, + } + require.Equal(t, "x = 5", spelling("", stmt)) + require.Equal(t, "x = 5 # as the file has it", spelling("x = 5 # as the file has it", stmt)) +} + // Plan §12: a multiline string literal is one eval operand on one line, its // control characters escaped, while the source prints the statement's own // lines, so the two spellings of one string sit together. @@ -906,7 +919,7 @@ d, l, r, n, copied.age, tag`) require.Equal(t, []string{"assign d", "assign d", "assign l, r", "assign l, _, n", "assign copied, tag"}, planLabels(plans)) require.Equal(t, `assign d source - d = (Twice(d) + 1) + d = Twice(d) + 1 execute %t0 = eval I64 Twice(d) + 1 @@ -1011,7 +1024,7 @@ n, o, k, p, q, one, acc`) // level in. require.Equal(t, ` assign t source - t = (a + 1) + t = a + 1 execute %t0 = eval I64 a + 1 @@ -1022,7 +1035,7 @@ n, o, k, p, q, one, acc`) // Row 14: a direct scalar output is a plain store. require.Equal(t, ` assign res source - res = (t * 2) + res = t * 2 execute %t0 = eval I64 t * 2 @@ -1033,7 +1046,7 @@ n, o, k, p, q, one, acc`) // Row 14i: a heap output takes an owned outcome and releases what it held. require.Equal(t, ` assign out source - out = (s ⊕ "!") + out = s ⊕ "!" execute %t0 = eval owned Str s ⊕ "!" @@ -1069,7 +1082,7 @@ n, o, k, p, q, one, acc`) // Row 14a: a rejected gate leaves an output holding what it held. require.Equal(t, ` assign out source - out = (n > 0) (s ⊕ "?") + out = n > 0 s ⊕ "?" execute %t0 = check I64 n > 0 @@ -1119,7 +1132,7 @@ x, fresh, t, u, hc, bc`) // An existing target keeps its value where the gate rejects. require.Equal(t, `assign x source - x = (n > 0) 5 + x = n > 0 5 execute %t0 = check I64 n > 0 @@ -1132,7 +1145,7 @@ x, fresh, t, u, hc, bc`) // A fresh target holds zero there, and has no old value to release. require.Equal(t, `assign fresh source - fresh = (n > 9) t + fresh = n > 9 t execute %t0 = check I64 n > 9 @@ -1146,7 +1159,7 @@ x, fresh, t, u, hc, bc`) // owner's old value. require.Equal(t, `assign t, u source - t, u = (n > 0) u, t + t, u = n > 0 u, t execute %t0 = check I64 n > 0 @@ -1162,7 +1175,7 @@ x, fresh, t, u, hc, bc`) // region like any value. require.Equal(t, `assign x source - x = (arr[1] > (-1)) (arr[9] || 8) + x = arr[1] > -1 arr[9] || 8 execute %t0 = check I64 arr[1] > (-1) [on-oob=skip] @@ -1179,7 +1192,7 @@ x, fresh, t, u, hc, bc`) // The gate only tests the check, so the string the check built is released. require.Equal(t, `assign hc source - hc = (MkStr(n) > "a") 7 + hc = MkStr(n) > "a" 7 execute %t0 = check owned Str MkStr(n) > "a" @@ -1193,7 +1206,7 @@ x, fresh, t, u, hc, bc`) // A binding the check read stays its owner's. require.Equal(t, `assign bc source - bc = (t > "abc") 1 + bc = t > "abc" 1 execute %t0 = check borrowed(t) Str t > "abc" @@ -1207,7 +1220,7 @@ x, fresh, t, u, hc, bc`) // built is released where the gate admitted it. require.Equal(t, `assign _ source - _ = (n > 0) MkStr(n) + _ = n > 0 MkStr(n) execute %t0 = check I64 n > 0 @@ -1282,7 +1295,7 @@ x, three, t, u, lb`) // built is released. require.Equal(t, `assign three source - three = (n > 0) && (MkStr(n) > "a") && (MkStr(x) > "a") 7 + three = n > 0 && MkStr(n) > "a" && MkStr(x) > "a" 7 execute %t0 = @@ -1304,7 +1317,7 @@ x, three, t, u, lb`) // is only tested. require.Equal(t, `assign t source - t = ((MkStr(n) > "a") && MkStr(x)) + t = MkStr(n) > "a" && MkStr(x) execute %t0 = @@ -1322,7 +1335,7 @@ x, three, t, u, lb`) // old value: where a gate moves both strings of a swap, this copies both. require.Equal(t, `assign t, u source - t, u = ((n > 0) && u), t + t, u = n > 0 && u, t execute %t0 = @@ -1342,7 +1355,7 @@ x, three, t, u, lb`) // skips it where the read fails. require.Equal(t, `assign x source - x = (((n > 0) && (n > 1)) && arr[9]) + x = n > 0 && n > 1 && arr[9] execute %t0 = @@ -1359,7 +1372,7 @@ x, three, t, u, lb`) // A last in a gate's region is numbered after the gate's check. require.Equal(t, `assign x source - x = (n > 0) ((n > 2) && 10) + x = n > 0 n > 2 && 10 execute %t0 = check I64 n > 0 @@ -1376,7 +1389,7 @@ x, three, t, u, lb`) // A discard keeps nothing: what the final side built is released. require.Equal(t, `assign _ source - _ = ((n > 0) && MkStr(n)) + _ = n > 0 && MkStr(n) execute %t0 = @@ -1393,7 +1406,7 @@ x, three, t, u, lb`) // what the check built is released where it failed. require.Equal(t, `assign lb source - lb = ((n > 0) && (MkStr(n) > "a")) + lb = n > 0 && MkStr(n) > "a" execute %t0 = @@ -1437,7 +1450,7 @@ x, g, s`) require.Equal(t, `assign x source - x = (a > 2) + x = a > 2 execute %t0 = check I64 a > 2 @@ -1447,7 +1460,7 @@ x, g, s`) `, plans[3].Render(false)) require.Equal(t, `assign g source - g = (n > 0) (a > 2) + g = n > 0 a > 2 execute %t0 = check I64 n > 0 @@ -1459,7 +1472,7 @@ x, g, s`) `, plans[4].Render(false)) require.Equal(t, `assign s source - s = (MkStr(a) > "zzz") + s = MkStr(a) > "zzz" execute %t0 = check owned Str MkStr(a) > "zzz" @@ -1530,7 +1543,7 @@ m`) // The invocation reads a binding's heap value and takes a temporary's. require.Equal(t, `print source - h, (h ⊕ "!") + h, h ⊕ "!" execute %t0 = eval borrowed Str h @@ -1548,7 +1561,7 @@ m`) `, plans[5].Render(true)) require.Equal(t, `print source - ([1 2] ⊕ [3]) + [1 2] ⊕ [3] execute %t0 = eval owned [I64] [1 2] ⊕ [3] @@ -1610,7 +1623,7 @@ keep, fresh, s, h1, h2, r`) // An existing target keeps its value. require.Equal(t, `assign keep source - keep = (keep * arr[5]) + keep = keep * arr[5] execute %t0 = eval I64 keep * arr[5] [on-oob=skip] @@ -1623,7 +1636,7 @@ keep, fresh, s, h1, h2, r`) // (tests/cond/value_cond_expr pins that at run time). require.Equal(t, `assign fresh source - fresh = (Loud(1) + arr[9]) + fresh = Loud(1) + arr[9] execute %t0 = eval I64 Loud(1) + arr[9] [on-oob=skip] @@ -1635,7 +1648,7 @@ keep, fresh, s, h1, h2, r`) // the mapping replaced it. require.Equal(t, `assign s source - s = (s ⊕ sarr[9]) + s = s ⊕ sarr[9] execute %t0 = eval owned Str s ⊕ sarr[9] [on-oob=skip] @@ -1740,7 +1753,7 @@ a, s, c, g, p, q, r, w`) // A fresh target and an existing one read alike: the first always yields. require.Equal(t, `assign a source - a = (arr[9] || (-1)) + a = arr[9] || -1 execute %t0 = @@ -1756,7 +1769,7 @@ a, s, c, g, p, q, r, w`) // built is released where the fallback ran. require.Equal(t, `assign s source - s = (sarr[9] || h) + s = sarr[9] || h execute %t0 = @@ -1773,7 +1786,7 @@ a, s, c, g, p, q, r, w`) // A chain is one first, however it is grouped. require.Equal(t, `assign c source - c = ((arr[9] || arr[8]) || (-3)) + c = arr[9] || arr[8] || -3 execute %t0 = @@ -1791,7 +1804,7 @@ a, s, c, g, p, q, r, w`) // value. require.Equal(t, `assign g source - g = (arr[9] || arr[8]) + g = arr[9] || arr[8] execute %t0 = @@ -1806,7 +1819,7 @@ a, s, c, g, p, q, r, w`) // A discard releases each owned side where it ran. require.Equal(t, `assign _ source - _ = (sarr[9] || (h ⊕ "?")) + _ = sarr[9] || (h ⊕ "?") execute %t0 = @@ -1823,7 +1836,7 @@ a, s, c, g, p, q, r, w`) // The eval after a first takes the ID after its sides. require.Equal(t, `assign p, q source - p, q = (arr[9] || (-1)), 5 + p, q = arr[9] || -1, 5 execute %t0 = @@ -1840,7 +1853,7 @@ a, s, c, g, p, q, r, w`) // A side may wrap its read, and fails where the read does. require.Equal(t, `assign w source - w = ((arr[9] + 1) || (-1)) + w = (arr[9] + 1) || -1 execute %t0 = @@ -1854,7 +1867,7 @@ a, s, c, g, p, q, r, w`) `, plans[13].Render(false)) require.Equal(t, ` assign res source - res = (v[i] || (-1)) + res = v[i] || -1 execute %t0 = @@ -1906,7 +1919,7 @@ s, t, h, g`) // the mapping always commits. require.Equal(t, `assign x source - x = ((a > 2) || 7) + x = a > 2 || 7 execute %t0 = @@ -1921,7 +1934,7 @@ s, t, h, g`) // A check as the last side can fail, so the binding keeps its value. require.Equal(t, `assign n source - n = ((a > 9) || (a > 1)) + n = a > 9 || a > 1 execute %t0 = @@ -1938,7 +1951,7 @@ s, t, h, g`) // the first's outcome. require.Equal(t, `assign z source - z = (((a > 0) && 11) || 13) + z = a > 0 && 11 || 13 execute %t0 = @@ -1957,7 +1970,7 @@ s, t, h, g`) // sides. Where no side yields, a fresh binding holds its zero. require.Equal(t, `assign u source - u = (((a > 9) && 1) || ((b > 0) && 2)) + u = a > 9 && 1 || b > 0 && 2 execute %t0 = @@ -1979,7 +1992,7 @@ s, t, h, g`) // nested last's final eval included. require.Equal(t, `assign c source - c = (((1 < 2) && arr[9]) || (-1)) + c = 1 < 2 && arr[9] || -1 execute %t0 = @@ -1998,7 +2011,7 @@ s, t, h, g`) // gives, as the last's final eval does. require.Equal(t, `assign d source - d = (((arr[9] > 0) && 1) || (-1)) + d = arr[9] > 0 && 1 || -1 execute %t0 = @@ -2017,7 +2030,7 @@ s, t, h, g`) // comparison does, and what it built is released where the fallback ran. require.Equal(t, `assign s source - s = ((sarr[9] > "a") || h) + s = sarr[9] > "a" || h execute %t0 = @@ -2035,7 +2048,7 @@ s, t, h, g`) // what it built is released once it is compared. require.Equal(t, `assign t source - t = (((MkStr(a) > "a") && MkStr(b)) || h) + t = MkStr(a) > "a" && MkStr(b) || h execute %t0 = @@ -2055,7 +2068,7 @@ s, t, h, g`) // nested last's own sides included. require.Equal(t, `assign p, q source - p, q = (((a > 0) && 11) || 13), 5 + p, q = a > 0 && 11 || 13, 5 execute %t0 = @@ -2077,7 +2090,7 @@ s, t, h, g`) // skips the outcome from there just as a side of its own would. require.Equal(t, `assign g source - g = (((a > 0) && sarr[9]) || ((b > 0) && sarr[1])) + g = a > 0 && sarr[9] || b > 0 && sarr[1] execute %t0 = diff --git a/docs/Pluto IR Plan.md b/docs/Pluto IR Plan.md index a8ca7462..6832d079 100644 --- a/docs/Pluto IR Plan.md +++ b/docs/Pluto IR Plan.md @@ -740,10 +740,12 @@ as in the source with each of its line breaks escaped the same way A plan's `source` follows the opposite rule, since it is the whole statement rather than an operand: the label stands alone and the statement's own lines sit one level in, so a block literal reads as it is laid out (decided -2026-11-23). What it renders is the ast's spelling of the statement, not the -file's bytes, so an operator root carries the pair it wraps itself in -(`d = (Twice(d) + 1)`) and a block literal's rows carry the ast's own -indentation. Within a line, everything a reader could not otherwise see is +2026-11-23). What it renders is the file's own text: the lines the statement +spans, dedented to the one it starts on, each cut before a comment that line +ends with. So the parens the ast adds to spell out its own nesting are absent +(`d = Twice(d) + 1`, not `d = (Twice(d) + 1)`), and an implicit +multiplication reads as it was typed (`imp = 5a`). A statement no file spells +— one a caller built — falls back to the ast's rendering. Within a line, everything a reader could not otherwise see is escaped — a tab, a control, and every rune Unicode calls unprintable, the format and separator characters among them — so a source never breaks the layout. Two statements still render alike where they hold the same text, a @@ -761,7 +763,7 @@ section's indent, and the operand beside it is exact. ```text assign x source - x = ((data[i] || other[j]) || (-1)) + x = data[i] || other[j] || -1 execute %t0 = @@ -786,7 +788,7 @@ transfer (decided 2026-11-20). ```text assign v source - v = ((n > 2) && 10) + v = n > 2 && 10 execute %t0 = @@ -809,7 +811,7 @@ whatever the condition. ```text assign x source - x = (n > 0) 5 + x = n > 0 5 execute %t0 = check I64 n > 0 @@ -1432,7 +1434,7 @@ in source order. ```text print source - "n: -n", h, (h ⊕ "!") + "n: -n", h, h ⊕ "!" execute %t0 = eval borrowed Str h @@ -1541,7 +1543,7 @@ freshness. ```text assign skeep source - skeep = (skeep ⊕ sarr[9]) + skeep = skeep ⊕ sarr[9] execute %t0 = eval owned Str skeep ⊕ sarr[9] [on-oob=skip] @@ -1626,7 +1628,7 @@ either way. ```text assign s source - s = (sarr[9] || h) + s = sarr[9] || h execute %t0 = @@ -1742,7 +1744,7 @@ that outcome and holds the statement's values in its region. ```text assign s source - s = (MkStr(n) > "a") t + s = MkStr(n) > "a" t execute %t0 = check owned Str MkStr(n) > "a" @@ -1808,7 +1810,7 @@ before the final one is a comparison, a `check` that is only tested, and the ```text assign t source - t = ((MkStr(n) > "a") && MkStr(x)) + t = MkStr(n) > "a" && MkStr(x) execute %t0 = @@ -1876,7 +1878,7 @@ where the comparison holds; where it fails, the binding carries ```text assign s source - s = (MkStr(a) > "zzz") + s = MkStr(a) > "zzz" execute %t0 = check owned Str MkStr(a) > "zzz" @@ -1938,7 +1940,7 @@ and any other side is an `eval`. ```text assign t source - t = ((MkStr(a) > "a") && MkStr(b)) || h + t = MkStr(a) > "a" && MkStr(b) || h execute %t0 = From 74c352263223415165cbbdfe3a851ffd50ab8d8c Mon Sep 17 00:00:00 2001 From: Tejas Date: Mon, 23 Nov 2026 18:27:33 +0530 Subject: [PATCH 07/39] fix(lexer): leave a string's own characters alone when quoting a statement MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Text moved every line of a span left and trimmed every line's trailing space, including the lines a string literal runs into, where those characters are what the string holds. Two reviews found four ways that shows, each on a program that compiles without a single error. A function body chopped its strings. `s = "line one` with `line two"` flush-left under a four-space body lost four runes of content, printing ` two"`, and a closing line shorter than the indentation vanished whole, leaving the quote open. A line a string runs into is no longer moved. Trailing space inside a string disappeared even at the script root: `"hello `, a line of one space and a line of one tab all rendered as if empty, so three different strings rendered alike — which is what §12 says cannot happen, and which reinstated, one stage earlier, the space-only line a3d5aaf had just fixed. The pir tests passed throughout because they hand Head.Source over directly, never reaching the lexer. A line a string runs into is no longer trimmed. A table's `:` header may hang two columns left of its rows, so a body's header can start left of its own statement; dedenting by the statement's indentation deleted it. The dedent is now the least indentation any line of the span has, which keeps the header and its alignment both. Text panicked on a column below one rather than reporting no span. Tests: the four cases in the lexer, the two string shapes through the parser, and TestSpellingReparses, which parses each statement's spelling on its own and compares the statement it gets back — an oracle that holds whatever the span drops or adds. Each fix dies under one mutant, named. Lines is unexported, since Text is its only caller and it hands out the slice it keeps. The renderer's comments now say the source is the file's text with the ast as its fallback. Co-Authored-By: Claude Opus 5 --- docs/Pluto IR Plan.md | 3 +- lexer/lexer.go | 72 +++++++++++++++++++++++++++---------- lexer/lexer_test.go | 7 ++++ parser/scriptparser_test.go | 54 +++++++++++++++++++++++++++- pir/pir_test.go | 4 +-- pir/print.go | 10 +++--- 6 files changed, 122 insertions(+), 28 deletions(-) diff --git a/docs/Pluto IR Plan.md b/docs/Pluto IR Plan.md index 6832d079..ec0a1d7c 100644 --- a/docs/Pluto IR Plan.md +++ b/docs/Pluto IR Plan.md @@ -745,7 +745,8 @@ spans, dedented to the one it starts on, each cut before a comment that line ends with. So the parens the ast adds to spell out its own nesting are absent (`d = Twice(d) + 1`, not `d = (Twice(d) + 1)`), and an implicit multiplication reads as it was typed (`imp = 5a`). A statement no file spells -— one a caller built — falls back to the ast's rendering. Within a line, everything a reader could not otherwise see is +— one a caller built — falls back to the ast's rendering. Within a line, +everything a reader could not otherwise see is escaped — a tab, a control, and every rune Unicode calls unprintable, the format and separator characters among them — so a source never breaks the layout. Two statements still render alike where they hold the same text, a diff --git a/lexer/lexer.go b/lexer/lexer.go index 505d7f4f..5ffb55b4 100644 --- a/lexer/lexer.go +++ b/lexer/lexer.go @@ -18,8 +18,9 @@ type Lexer struct { lineOffset int // line number column int // column number in the line - lines []string // the input's physical lines, read on demand - comments map[int]int // the column a line's comment starts at, by line + src []string // the input's physical lines, read on demand + comments map[int]int // the column a line's comment starts at, by line + stringBreaks map[int]bool // the lines a string literal runs past the end of blocks []block // the open indented blocks; innermost last pending queue // tokens decided but not yet returned @@ -104,40 +105,70 @@ func (l *Lexer) noteComment() { l.comments[l.lineOffset] = l.column } -// Lines returns the source as its physical lines, each terminator the +// noteStringBreak records that a string literal runs past the end of the line +// being read, so that quoting a statement leaves the next line's own +// characters alone: they are the string's content, not the file's layout. +func (l *Lexer) noteStringBreak() { + if l.stringBreaks == nil { + l.stringBreaks = make(map[int]bool) + } + l.stringBreaks[l.lineOffset] = true +} + +// lines returns the source as its physical lines, each terminator the // language counts as one — LF, CRLF and CR alike, as LogicalRune reads them — // ending exactly one line. -func (l *Lexer) Lines() []string { - if l.lines == nil { +func (l *Lexer) lines() []string { + if l.src == nil { text := strings.ReplaceAll(strings.ReplaceAll(string(l.input), "\r\n", "\n"), "\r", "\n") - l.lines = strings.Split(text, "\n") + l.src = strings.Split(text, "\n") } - return l.lines + return l.src } -// Text is the source a statement is spelled with: the lines it spans, each -// cut before any comment that line ends with, dedented by the indentation of -// the line it starts on, and with trailing space dropped. Lines and columns -// are the ones a token carries, counted from one. It is empty where the span -// names no line of this input. +// dedent is how far Text may move a span's lines left: the indentation of the +// line it starts on, or the least a line in the span has where that is less, +// as a table's hanging `:` header is. A line a string literal runs into holds +// content rather than layout, so it neither moves nor counts. +func (l *Lexer) dedent(lines []string, startLine, startColumn, endLine int) int { + dedent := startColumn - 1 + for n := startLine; n <= endLine && dedent > 0; n++ { + if l.stringBreaks[n-1] || strings.TrimSpace(lines[n-1]) == "" { + continue + } + dedent = min(dedent, len(lines[n-1])-len(strings.TrimLeft(lines[n-1], " "))) + } + return dedent +} + +// Text is the source a statement is spelled with: the lines it spans, each cut +// before any comment that line ends with, moved left to the indentation of the +// line it starts on, and with trailing space dropped. A line a string literal +// runs into keeps its own characters, since they are what the string holds. +// Lines and columns are the ones a token carries, counted from one; a span +// naming no line of this input is empty. A comment is cut only on a line the +// lexer has already read. func (l *Lexer) Text(startLine, startColumn, endLine int) string { - lines := l.Lines() - if startLine < 1 || startLine > endLine || endLine > len(lines) { + lines := l.lines() + if startLine < 1 || startColumn < 1 || startLine > endLine || endLine > len(lines) { return "" } + dedent := l.dedent(lines, startLine, startColumn, endLine) spelled := make([]string, 0, endLine-startLine+1) for n := startLine; n <= endLine; n++ { runes := []rune(lines[n-1]) if column, commented := l.comments[n]; commented { runes = runes[:min(column-1, len(runes))] } - if dedent := startColumn - 1; dedent < len(runes) { - runes = runes[dedent:] - } else { - runes = nil + if !l.stringBreaks[n-1] { + runes = runes[min(dedent, len(runes)):] } - spelled = append(spelled, strings.TrimRight(string(runes), " \t")) + line := string(runes) + if !l.stringBreaks[n] { + line = strings.TrimRight(line, " \t") + } + spelled = append(spelled, line) } return strings.Join(spelled, "\n") } @@ -579,6 +610,9 @@ func (l *Lexer) readString(tok token.Token) (string, *token.CompileError) { } for l.curr != '"' && !l.atEOF() { + if l.curr == '\n' { + l.noteStringBreak() + } if l.curr == 0 { setError("NUL character is not allowed in string literals") l.readRune() diff --git a/lexer/lexer_test.go b/lexer/lexer_test.go index b53023e9..12213443 100644 --- a/lexer/lexer_test.go +++ b/lexer/lexer_test.go @@ -1425,6 +1425,9 @@ func TestDecodeStringEscapePhysicalBreak(t *testing.T) { func TestText(t *testing.T) { const script = "a = 1 # one\nm = [\n # a row\n 2 3\n]\n" const body = "r = G(x)\n m = [\n 2 3\n ]\n" + const str = "w = \"hello \n \nworld\"\n" + const bodyStr = "r = G(x)\n s = \"line one\nline two\"\n" + const hanging = "r = G(x)\n t = [\n : Name Score\n \"Ada\" 1\n ]\n" cases := []struct { name string src string @@ -1434,8 +1437,12 @@ func TestText(t *testing.T) { {"OneLineCutsItsComment", script, 1, 1, 1, "a = 1"}, {"LinesKeepTheirShape", script, 2, 1, 5, "m = [\n\n 2 3\n]"}, {"DedentedToItsFirstLine", body, 2, 5, 4, "m = [\n 2 3\n]"}, + {"StringContentKeepsItsSpaces", str, 1, 1, 3, "w = \"hello \n \nworld\""}, + {"StringContentIsNotMovedLeft", bodyStr, 2, 5, 3, "s = \"line one\nline two\""}, + {"HangingHeaderKeepsItsColon", hanging, 2, 5, 5, " t = [\n: Name Score\n \"Ada\" 1\n ]"}, {"BeforeTheInput", script, 0, 1, 1, ""}, {"PastTheInput", script, 1, 1, 99, ""}, + {"BeforeTheFirstColumn", script, 1, 0, 1, ""}, {"Backwards", script, 3, 1, 2, ""}, } for _, tc := range cases { diff --git a/parser/scriptparser_test.go b/parser/scriptparser_test.go index 262f2e70..f61c5c56 100644 --- a/parser/scriptparser_test.go +++ b/parser/scriptparser_test.go @@ -1,6 +1,7 @@ package parser import ( + "fmt" "strings" "testing" @@ -67,6 +68,10 @@ m = [ ] long = a + 1 +w = "hello + + +world" "out: -b -n" ` want := []string{ @@ -76,6 +81,7 @@ long = "f = -8 >> 1", "m = [\n 1 2\n 3 4\n]", "long =\n a + 1", + "w = \"hello \n \n\t\nworld\"", `"out: -b -n"`, } @@ -97,11 +103,57 @@ long = } } +// A statement's spelling holds everything the statement does, so parsing it +// on its own gives the same statement back. That catches a span that dropped +// or added a character where no golden names it. +func TestSpellingReparses(t *testing.T) { + scripts := []string{ + "b = a + 2 * 3\n", + "imp = 5a\n", + "f = -8 >> 1 # arithmetic right shift\n", + "m = [\n 1 2\n 3 4\n]\n", + "long =\n a + 1\n", + "w = \"hello \n \n\t\nworld\"\n", + "s = \"a\nb\"\n\"out: -s\"\n", + } + for i, script := range scripts { + t.Run(fmt.Sprintf("script%d", i), func(t *testing.T) { + sp := NewScriptParser(lexer.New("TestSpellingReparses", script)) + program := sp.Parse() + require.Empty(t, sp.Errors(), "unexpected parse errors: %v", sp.Errors()) + + for _, stmt := range program.Statements { + src, ok := spelled(stmt) + require.True(t, ok, "statement %T carries no spelling", stmt) + + again := NewScriptParser(lexer.New("TestSpellingReparses", src+"\n")) + reparsed := again.Parse() + require.Empty(t, again.Errors(), "reparsing %q: %v", src, again.Errors()) + require.Len(t, reparsed.Statements, 1, "reparsing %q", src) + require.Equal(t, stmt.String(), reparsed.Statements[0].String(), "reparsing %q", src) + } + }) + } +} + +// spelled returns the source a statement carries, where it carries one. +func spelled(stmt ast.Statement) (string, bool) { + switch s := stmt.(type) { + case *ast.LetStatement: + return s.Src, true + case *ast.PrintStatement: + return s.Src, true + } + return "", false +} + // Plan §12: a statement inside a function body is spelled dedented to its own // first line, so a plan can place it at its own level. func TestStatementSpellingInBody(t *testing.T) { const code = `r = G(x) t = x * 2 # doubled + s = "line one +line two" r = t + 1 ` l := lexer.New("TestStatementSpellingInBody", code) @@ -119,7 +171,7 @@ func TestStatementSpellingInBody(t *testing.T) { spelled = append(spelled, inner.(*ast.LetStatement).Src) } } - require.Equal(t, []string{"t = x * 2", "r = t + 1"}, spelled) + require.Equal(t, []string{"t = x * 2", "s = \"line one\nline two\"", "r = t + 1"}, spelled) } func TestInvalidAssignment(t *testing.T) { diff --git a/pir/pir_test.go b/pir/pir_test.go index 28bc0d24..ac203fad 100644 --- a/pir/pir_test.go +++ b/pir/pir_test.go @@ -1551,8 +1551,8 @@ func TestRenderSkip(t *testing.T) { } } -// Plan §12: a plan's source prints as the ast's own lines, one level in, so a -// literal that spans lines reads as it is laid out. Every character a reader +// Plan §12: a plan's source prints as the lines it was given, one level in, +// so a literal that spans lines reads as it is laid out. Every character a reader // could not otherwise see is escaped, a line of spaces keeps its own // indentation at either level, and only an empty line stays bare, since those // separate a plan's sections. diff --git a/pir/print.go b/pir/print.go index f03f8916..15efa4dd 100644 --- a/pir/print.go +++ b/pir/print.go @@ -97,11 +97,11 @@ func writeNodes(b *strings.Builder, indent string, nodes []Node, expanded bool) } // writeHead writes what every plan opens with: its header, its source, and -// the line that opens its execute region. The source prints as the -// statement's own lines, one level in, so a literal that spans lines reads as -// the ast spells it, and every other character a reader cannot see is still -// escaped. A node's operand stays one line, line breaks escaped with it -// (plan §12). +// the line that opens its execute region. The source prints as the lines its +// file spells the statement with, one level in, so a literal that spans lines +// reads as it is laid out, with every character a reader cannot see still +// escaped; a statement no file spells carries the ast's rendering instead. A +// node's operand stays one line, line breaks escaped with it (plan §12). func writeHead(b *strings.Builder, head Head) { fmt.Fprintf(b, "%s\n", head.Label) b.WriteString(" source\n") From 1f7eb9a3c4076821e5984313a2b029a18c15c5bd Mon Sep 17 00:00:00 2001 From: Tejas Date: Mon, 23 Nov 2026 18:55:49 +0530 Subject: [PATCH 08/39] fix(lexer): measure a span's indentation after cutting its comments MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A comment inside a statement of several lines held the whole statement back. dedent read the raw line, so a comment at column one — which Pluto allows anywhere — measured as no indentation at all and the statement kept its body's four spaces, printing `out =` at sixteen columns where it belongs at twelve. A tab-indented comment did the same, since counting leading spaces stops at the tab, and a comment at column two left one. Text now cuts every line's comment once, measures the dedent over what is left, and applies the dedent and the trailing trim to those same lines. A line its comment leaves blank holds nothing, so it no longer counts. Two reviews reported it and gave the same two shapes, both tested: a comment at column one inside a body's block literal, and one indented with a tab. `b = ((a))` joins the spelling expectations, since parens an author wrote are what this change is for, and only an exact expectation pins them — TestSpellingReparses compares the ast's rendering, which reads `b = ((a))` and `b = a` alike. Co-Authored-By: Claude Opus 5 --- lexer/lexer.go | 32 ++++++++++++++++++++++---------- lexer/lexer_test.go | 4 ++++ parser/scriptparser_test.go | 9 ++++++--- 3 files changed, 32 insertions(+), 13 deletions(-) diff --git a/lexer/lexer.go b/lexer/lexer.go index 5ffb55b4..c95523d6 100644 --- a/lexer/lexer.go +++ b/lexer/lexer.go @@ -129,14 +129,21 @@ func (l *Lexer) lines() []string { // dedent is how far Text may move a span's lines left: the indentation of the // line it starts on, or the least a line in the span has where that is less, // as a table's hanging `:` header is. A line a string literal runs into holds -// content rather than layout, so it neither moves nor counts. -func (l *Lexer) dedent(lines []string, startLine, startColumn, endLine int) int { +// content rather than layout, and a line its comment leaves blank holds +// nothing, so neither counts. The span's lines come with their comments +// already cut, since a comment may sit at any column and would otherwise +// measure as the whole statement's indentation. +func (l *Lexer) dedent(span [][]rune, startLine, startColumn int) int { dedent := startColumn - 1 - for n := startLine; n <= endLine && dedent > 0; n++ { - if l.stringBreaks[n-1] || strings.TrimSpace(lines[n-1]) == "" { + for i, runes := range span { + if dedent == 0 { + break + } + line := string(runes) + if l.stringBreaks[startLine+i-1] || strings.TrimSpace(line) == "" { continue } - dedent = min(dedent, len(lines[n-1])-len(strings.TrimLeft(lines[n-1], " "))) + dedent = min(dedent, len(line)-len(strings.TrimLeft(line, " "))) } return dedent } @@ -154,21 +161,26 @@ func (l *Lexer) Text(startLine, startColumn, endLine int) string { return "" } - dedent := l.dedent(lines, startLine, startColumn, endLine) - spelled := make([]string, 0, endLine-startLine+1) + span := make([][]rune, 0, endLine-startLine+1) for n := startLine; n <= endLine; n++ { runes := []rune(lines[n-1]) if column, commented := l.comments[n]; commented { runes = runes[:min(column-1, len(runes))] } - if !l.stringBreaks[n-1] { + span = append(span, runes) + } + + dedent := l.dedent(span, startLine, startColumn) + spelled := make([]string, len(span)) + for i, runes := range span { + if !l.stringBreaks[startLine+i-1] { runes = runes[min(dedent, len(runes)):] } line := string(runes) - if !l.stringBreaks[n] { + if !l.stringBreaks[startLine+i] { line = strings.TrimRight(line, " \t") } - spelled = append(spelled, line) + spelled[i] = line } return strings.Join(spelled, "\n") } diff --git a/lexer/lexer_test.go b/lexer/lexer_test.go index 12213443..790a4a4d 100644 --- a/lexer/lexer_test.go +++ b/lexer/lexer_test.go @@ -1428,6 +1428,8 @@ func TestText(t *testing.T) { const str = "w = \"hello \n \nworld\"\n" const bodyStr = "r = G(x)\n s = \"line one\nline two\"\n" const hanging = "r = G(x)\n t = [\n : Name Score\n \"Ada\" 1\n ]\n" + const flushComment = "r = G(x)\n m = [\n# flush left\n 2 3\n ]\n" + const tabComment = "r = G(x)\n m = [\n\t# tabbed\n 2 3\n ]\n" cases := []struct { name string src string @@ -1440,6 +1442,8 @@ func TestText(t *testing.T) { {"StringContentKeepsItsSpaces", str, 1, 1, 3, "w = \"hello \n \nworld\""}, {"StringContentIsNotMovedLeft", bodyStr, 2, 5, 3, "s = \"line one\nline two\""}, {"HangingHeaderKeepsItsColon", hanging, 2, 5, 5, " t = [\n: Name Score\n \"Ada\" 1\n ]"}, + {"AFlushLeftCommentDoesNotHoldTheSpanBack", flushComment, 2, 5, 5, "m = [\n\n 2 3\n]"}, + {"ATabbedCommentDoesNotHoldTheSpanBack", tabComment, 2, 5, 5, "m = [\n\n 2 3\n]"}, {"BeforeTheInput", script, 0, 1, 1, ""}, {"PastTheInput", script, 1, 1, 99, ""}, {"BeforeTheFirstColumn", script, 1, 0, 1, ""}, diff --git a/parser/scriptparser_test.go b/parser/scriptparser_test.go index f61c5c56..105a2770 100644 --- a/parser/scriptparser_test.go +++ b/parser/scriptparser_test.go @@ -58,7 +58,7 @@ func TestAssign(t *testing.T) { // typed, a comment the line ends with is cut, and a statement of several // lines keeps its own shape dedented to its first line. func TestStatementSpelling(t *testing.T) { - const script = `b = a + 2 * 3 + const script = `b = ((a)) n = -a imp = 5a f = -8 >> 1 # arithmetic right shift @@ -75,7 +75,7 @@ world" "out: -b -n" ` want := []string{ - "b = a + 2 * 3", + "b = ((a))", "n = -a", "imp = 5a", "f = -8 >> 1", @@ -154,6 +154,9 @@ func TestStatementSpellingInBody(t *testing.T) { t = x * 2 # doubled s = "line one line two" + u = +# flush left + x + 1 r = t + 1 ` l := lexer.New("TestStatementSpellingInBody", code) @@ -171,7 +174,7 @@ line two" spelled = append(spelled, inner.(*ast.LetStatement).Src) } } - require.Equal(t, []string{"t = x * 2", "s = \"line one\nline two\"", "r = t + 1"}, spelled) + require.Equal(t, []string{"t = x * 2", "s = \"line one\nline two\"", "u =\n\n x + 1", "r = t + 1"}, spelled) } func TestInvalidAssignment(t *testing.T) { From 460050735ab616f4933e3561fd6b791e03451125 Mon Sep 17 00:00:00 2001 From: Tejas Date: Mon, 23 Nov 2026 22:27:22 +0530 Subject: [PATCH 09/39] refactor(pir): take a plan's source from the file and nowhere else MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The builder fell back to the ast's rendering where a statement carried no source of its own. Nothing produces that: the parser is the only place a let or a print statement is built, and both of its statement loops spell every one it returns. The fallback's only exercise was the test written for it. What a plan with no source actually wants is to say so, and it already does — validateHead rejects an empty head source, a rule TestValidateRejects and TestValidatePrintRejects both pin, and lowerPlanned turns that into an ICE. With the parser spelling nothing, compiling `a = 5` now reports internal: invalid plan for "a = 5": plan assign a has no source rendering rather than quietly printing a plausible source line and hiding the bug. Co-Authored-By: Claude Opus 5 --- compiler/pir.go | 13 ++----------- compiler/pir_test.go | 13 ------------- docs/Pluto IR Plan.md | 5 +++-- pir/print.go | 4 ++-- 4 files changed, 7 insertions(+), 28 deletions(-) diff --git a/compiler/pir.go b/compiler/pir.go index 7d817620..5765c66c 100644 --- a/compiler/pir.go +++ b/compiler/pir.go @@ -271,15 +271,6 @@ func (c *Compiler) planExprEligible(expr ast.Expression, reads bool) bool { return true } -// spelling is the source a plan quotes: what the file gave the statement, -// falling back to the ast's own rendering for a statement no file spells. -func spelling(src string, stmt ast.Statement) string { - if src != "" { - return src - } - return stmt.String() -} - // planOOBScope gives a node's index reads their scope (plan §9): a failed // read runs the fallback that follows its side of a first, and skips the // outcome otherwise. The router admits a read only in those two places. @@ -389,7 +380,7 @@ func (c *Compiler) buildLetPlan(stmt *ast.LetStatement, fn string) *pir.AssignPl nameParts[i] = ident.Value } plan := &pir.AssignPlan{ - Head: pir.Head{Label: "assign " + strings.Join(nameParts, ", "), Func: fn, Source: spelling(stmt.Src, stmt)}, + Head: pir.Head{Label: "assign " + strings.Join(nameParts, ", "), Func: fn, Source: stmt.Src}, Commit: make([]pir.Mapping, 0, len(stmt.Name)), } @@ -538,7 +529,7 @@ func (c *Compiler) mapNextTarget(plan *pir.AssignPlan, stmt *ast.LetStatement, o // string literal as itself, since print formats it in place, and any other // argument as the outcome of its eval. func (c *Compiler) buildPrintPlan(stmt *ast.PrintStatement, fn string) *pir.PrintPlan { - plan := &pir.PrintPlan{Head: pir.Head{Label: "print", Func: fn, Source: spelling(stmt.Src, stmt)}} + plan := &pir.PrintPlan{Head: pir.Head{Label: "print", Func: fn, Source: stmt.Src}} for _, expr := range stmt.Expression.Arguments { if lit, isLit := expr.(*ast.StringLiteral); isLit { plan.Args = append(plan.Args, pir.PrintArg{Literal: lit}) diff --git a/compiler/pir_test.go b/compiler/pir_test.go index 4ad791ab..4c4fba14 100644 --- a/compiler/pir_test.go +++ b/compiler/pir_test.go @@ -9,7 +9,6 @@ import ( "github.com/stretchr/testify/require" "github.com/thiremani/pluto/ast" "github.com/thiremani/pluto/pir" - "github.com/thiremani/pluto/token" "tinygo.org/x/go-llvm" ) @@ -823,18 +822,6 @@ copy, other, text`) require.True(t, plans[3].Commit[0].Target.HoldsHeap) } -// Plan §12: a plan quotes the source its file spells the statement with, and -// falls back to the ast's rendering for a statement no file spells. -func TestPlanSourceFallsBackToTheAst(t *testing.T) { - stmt := &ast.LetStatement{ - Token: token.Token{Type: token.ASSIGN, Literal: "="}, - Name: []*ast.Identifier{{Token: token.Token{Type: token.IDENT, Literal: "x"}, Value: "x"}}, - Value: []ast.Expression{&ast.IntegerLiteral{Token: token.Token{Type: token.INT, Literal: "5"}, Value: 5}}, - } - require.Equal(t, "x = 5", spelling("", stmt)) - require.Equal(t, "x = 5 # as the file has it", spelling("x = 5 # as the file has it", stmt)) -} - // Plan §12: a multiline string literal is one eval operand on one line, its // control characters escaped, while the source prints the statement's own // lines, so the two spellings of one string sit together. diff --git a/docs/Pluto IR Plan.md b/docs/Pluto IR Plan.md index ec0a1d7c..444724d0 100644 --- a/docs/Pluto IR Plan.md +++ b/docs/Pluto IR Plan.md @@ -744,8 +744,9 @@ sit one level in, so a block literal reads as it is laid out (decided spans, dedented to the one it starts on, each cut before a comment that line ends with. So the parens the ast adds to spell out its own nesting are absent (`d = Twice(d) + 1`, not `d = (Twice(d) + 1)`), and an implicit -multiplication reads as it was typed (`imp = 5a`). A statement no file spells -— one a caller built — falls back to the ast's rendering. Within a line, +multiplication reads as it was typed (`imp = 5a`). Every statement a plan is +built from comes from a file, and validation rejects a plan whose head carries +no source, so there is nothing to fall back to. Within a line, everything a reader could not otherwise see is escaped — a tab, a control, and every rune Unicode calls unprintable, the format and separator characters among them — so a source never breaks the diff --git a/pir/print.go b/pir/print.go index 15efa4dd..4ebb2ed6 100644 --- a/pir/print.go +++ b/pir/print.go @@ -100,8 +100,8 @@ func writeNodes(b *strings.Builder, indent string, nodes []Node, expanded bool) // the line that opens its execute region. The source prints as the lines its // file spells the statement with, one level in, so a literal that spans lines // reads as it is laid out, with every character a reader cannot see still -// escaped; a statement no file spells carries the ast's rendering instead. A -// node's operand stays one line, line breaks escaped with it (plan §12). +// escaped. A node's operand stays one line, line breaks escaped with it +// (plan §12). func writeHead(b *strings.Builder, head Head) { fmt.Fprintf(b, "%s\n", head.Label) b.WriteString(" source\n") From bca0ec994f7daf95d23b308892d2ed4b5e71a2cc Mon Sep 17 00:00:00 2001 From: Tejas Date: Mon, 23 Nov 2026 22:35:54 +0530 Subject: [PATCH 10/39] docs(ast): say a caller that builds a statement spells it too MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Src's comment still offered String() as what a statement carries where a file spelled none, which 4600507 removed. It matters more than a stale phrase usually would: NewScriptCompiler takes an ast a caller built, so the field's comment is where such a caller learns that a plan requires a spelling, and that validateHead rejects a plan without one. escapeControls kept the absolute claim that no two statements render alike, which 18eabfa narrowed in §12 for the reason a review gave: a physical tab and a `\t` escape render alike, and should. It now says what holds — two statements that differ never render alike. While here: 4600507's message names TestValidatePrintRejects for the rule that rejects a print plan with no source. The test is TestValidatePrint, whose NoSource case carries it. Co-Authored-By: Claude Opus 5 --- ast/ast.go | 4 ++-- pir/print.go | 7 ++++--- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/ast/ast.go b/ast/ast.go index 59885fbc..f1669b89 100644 --- a/ast/ast.go +++ b/ast/ast.go @@ -145,7 +145,7 @@ type LetStatement struct { Name []*Identifier Value []Expression Condition []Expression - Src string // the source the file spells it with; String() where a caller built it + Src string // the source the file spells it with; a plan requires one, so a caller that builds a statement sets it too } func (ls *LetStatement) statementNode() {} @@ -176,7 +176,7 @@ func (ls *LetStatement) String() string { type PrintStatement struct { Token token.Token // the first token of the expression Expression *CallExpression - Src string // the source the file spells it with; String() where a caller built it + Src string // the source the file spells it with; a plan requires one, so a caller that builds a statement sets it too } func (ps *PrintStatement) statementNode() {} diff --git a/pir/print.go b/pir/print.go index 4ebb2ed6..5c40172f 100644 --- a/pir/print.go +++ b/pir/print.go @@ -218,9 +218,10 @@ func logicalNewlines(s string) string { } // escapeControls spells out what a reader would not otherwise see, so that an -// operand stays on one physical line, a source line keeps its own, and no two -// statements render alike: a line terminator, a tab, and every rune Unicode -// calls unprintable, the format and separator characters among them. +// operand stays on one physical line, a source line keeps its own, and two +// statements that differ never render alike: a line terminator, a tab, and +// every rune Unicode calls unprintable, the format and separator characters +// among them. func escapeControls(s string) string { var b strings.Builder for _, r := range logicalNewlines(s) { From 8000a3d89d5e2e4e5a0444221bc182db81e8a144 Mon Sep 17 00:00:00 2001 From: Tejas Date: Mon, 23 Nov 2026 23:35:55 +0530 Subject: [PATCH 11/39] feat(token): give every token the runes that spell it MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A token carried where it starts and nothing about how far it runs, so quoting a statement had to rebuild it from whole lines and keep two side tables to undo what that swept in: where each line's comment begins, and which lines a string literal runs past. Both are bookkeeping for a reconstruction that offsets make unnecessary. Pos and Len say where a token's source spelling begins and how long it is. The lexer knows both already: tokenAt runs at the token's first rune, and lex leaves the input just past the token it returns, so one funnel gives every token its length — including the ':' and ']' the layout rules lex ahead of the line they start, which go through the queue rather than straight out, and which this was getting wrong until the funnel covered them too. A layout token spells no source and says so with a zero length. TestTokenExtents is the oracle: for every token a source spells, the runes at Pos run exactly as long as Len and read as the token's own spelling. Nothing uses the fields yet. Co-Authored-By: Claude Opus 5 --- lexer/lexer.go | 18 +++++++++++++++--- lexer/lexer_test.go | 33 +++++++++++++++++++++++++++++++++ token/token.go | 2 ++ 3 files changed, 50 insertions(+), 3 deletions(-) diff --git a/lexer/lexer.go b/lexer/lexer.go index c95523d6..77de7652 100644 --- a/lexer/lexer.go +++ b/lexer/lexer.go @@ -185,7 +185,9 @@ func (l *Lexer) Text(startLine, startColumn, endLine int) string { return strings.Join(spelled, "\n") } -// tokenAt makes a token at column on the line being read. +// tokenAt makes a token at column on the line being read. Len stays zero: +// the layout tokens this makes on their own spell no source, and lex measures +// the ones that do once they are whole. func (l *Lexer) tokenAt(tokenType token.TokenType, literal string, column int) token.Token { return token.Token{ FileName: l.FileName, @@ -193,6 +195,7 @@ func (l *Lexer) tokenAt(tokenType token.TokenType, literal string, column int) t Literal: literal, Line: l.lineOffset, Column: column, + Pos: l.position, } } @@ -208,7 +211,7 @@ func (l *Lexer) NextToken() (token.Token, *token.CompileError) { return next.tok, &token.CompileError{Token: next.tok, Msg: next.msg} } - tok, err := l.lex() + tok, err := l.measured() if tok.Type == token.NEWLINE && !l.lineBreak() { return l.NextToken() } @@ -281,7 +284,7 @@ func (l *Lexer) closes(column int) bool { // the error about it. A token carries one error, and lex reports none about // either character, so one from lex here would be a lexer bug. func (l *Lexer) queueLexed(msg string) { - tok, err := l.lex() + tok, err := l.measured() if err != nil { panic("internal: lex reported an error on the ']' or ':' that starts a line") } @@ -378,6 +381,15 @@ func (l *Lexer) dedentTo(n, column int, first rune) { } } +// measured lexes the next token and gives it the runes that spell it: lex +// leaves the input just past a token it returns, so its length is how far the +// position moved. Every token a source spells comes from here. +func (l *Lexer) measured() (token.Token, *token.CompileError) { + tok, err := l.lex() + tok.Len = l.position - tok.Pos + return tok, err +} + func (l *Lexer) lex() (token.Token, *token.CompileError) { var tok token.Token var err *token.CompileError diff --git a/lexer/lexer_test.go b/lexer/lexer_test.go index 790a4a4d..e6c79ad2 100644 --- a/lexer/lexer_test.go +++ b/lexer/lexer_test.go @@ -1477,3 +1477,36 @@ func TestTextLineEndings(t *testing.T) { }) } } + +// Every token a source spells carries the runes that spell it, so a caller +// can quote any span of the input from its tokens alone. A layout token +// spells nothing and says so with a zero length. +func TestTokenExtents(t *testing.T) { + const src = "a = 5 # one\nm = [\n 2 3\n]\ns = \"x\ny\"\nimp = 5a\n" + l := New("TestTokenExtents", src) + runes := []rune(src) + for { + tok, err := l.NextToken() + if tok.Type == token.EOF { + break + } + if err != nil { + t.Fatalf("unexpected error at %d:%d: %v", tok.Line, tok.Column, err) + } + switch tok.Type { + case token.INDENT, token.DEINDENT, token.NEWLINE: + continue + } + if tok.Len <= 0 { + t.Fatalf("token %q (type %d) at %d:%d spells no source", tok.Literal, int(tok.Type), tok.Line, tok.Column) + } + spelled := string(runes[tok.Pos : tok.Pos+tok.Len]) + want := tok.Literal + if tok.Type == token.STRING { + want = `"` + tok.Literal + `"` + } + if spelled != want { + t.Fatalf("token at %d:%d spells %q, want %q", tok.Line, tok.Column, spelled, want) + } + } +} diff --git a/token/token.go b/token/token.go index 2228c060..433981de 100644 --- a/token/token.go +++ b/token/token.go @@ -185,6 +185,8 @@ type Token struct { Literal string // source spelling; string contents retain escape sequences Line int Column int + Pos int // the token's first rune, counted from the input's start + Len int // its runes of source spelling; 0 for a token no source spells HadSpace bool // true if there was any space before this token } From cf72f5bc62f42c1bfcf79e5b91ebf311197edf5f Mon Sep 17 00:00:00 2001 From: Tejas Date: Mon, 23 Nov 2026 23:43:54 +0530 Subject: [PATCH 12/39] refactor(lexer): quote a statement from its tokens, not from whole lines MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Text rebuilt a statement from the lines it covered, so it swept in a comment the statement never reached and had to cut it back out, and it reshaped every line it took, so it had to be told which lines a string literal ran through. Those two side tables, the line cache they read, and the four bugs they cost are all bookkeeping for the reconstruction. Spelling takes the span instead: the input from the first token's start to the last token's end. A comment past the statement is simply not in it. A line after the first moves left by the indentation the first stands at, or by its own leading spaces where it has fewer, so nothing a line spells is ever cut — a table's hanging `:` keeps its colon without a span-wide minimum. The literals a statement spans say which lines hold a string's own characters: one a literal runs into is not moved, one it runs out of is not trimmed. The parser keeps what that needs as it consumes tokens: the last token a source spells, since the layout token a statement ends on reaches past it, and the string literals in between. Both reset per statement and die with it, where the maps lived as long as the lexer. One rendering change: a comment between two of a statement's own tokens now reads as the author wrote it, where it used to leave a blank line. No fixture or golden holds one, so none moved; §12 says so, and TestSpellingReparses gains the shape to pin that it still parses. The lexer loses 32 lines net. comments, stringBreaks, lines, dedent, Text, noteComment and noteStringBreak are gone. Co-Authored-By: Claude Opus 5 --- docs/Pluto IR Plan.md | 10 ++- lexer/lexer.go | 132 ++++++++++++++---------------------- lexer/lexer_test.go | 107 +++++++++++++++++------------ parser/parser.go | 34 ++++++++-- parser/scriptparser_test.go | 3 +- 5 files changed, 150 insertions(+), 136 deletions(-) diff --git a/docs/Pluto IR Plan.md b/docs/Pluto IR Plan.md index 444724d0..f4357cba 100644 --- a/docs/Pluto IR Plan.md +++ b/docs/Pluto IR Plan.md @@ -740,9 +740,13 @@ as in the source with each of its line breaks escaped the same way A plan's `source` follows the opposite rule, since it is the whole statement rather than an operand: the label stands alone and the statement's own lines sit one level in, so a block literal reads as it is laid out (decided -2026-11-23). What it renders is the file's own text: the lines the statement -spans, dedented to the one it starts on, each cut before a comment that line -ends with. So the parens the ast adds to spell out its own nesting are absent +2026-11-23). What it renders is the file's own text, from the statement's +first token to its last: a comment the statement does not reach is never in +it, while one between two of its own tokens is. Every line after the first +moves left to where the first stands, or by its own leading spaces where it +has fewer, so nothing a line spells is ever cut, and a line a string literal +runs through keeps the characters the string holds. So the parens the ast adds +to spell out its own nesting are absent (`d = Twice(d) + 1`, not `d = (Twice(d) + 1)`), and an implicit multiplication reads as it was typed (`imp = 5a`). Every statement a plan is built from comes from a file, and validation rejects a plan whose head carries diff --git a/lexer/lexer.go b/lexer/lexer.go index 77de7652..5ebe1cef 100644 --- a/lexer/lexer.go +++ b/lexer/lexer.go @@ -18,10 +18,6 @@ type Lexer struct { lineOffset int // line number column int // column number in the line - src []string // the input's physical lines, read on demand - comments map[int]int // the column a line's comment starts at, by line - stringBreaks map[int]bool // the lines a string literal runs past the end of - blocks []block // the open indented blocks; innermost last pending queue // tokens decided but not yet returned last token.TokenType // the last token returned, NEWLINE at the start; a line ending in a comma or '=' continues @@ -96,93 +92,70 @@ func (l *Lexer) createToken(tokenType token.TokenType, literal string, hadSpace return tok } -// noteComment records where the comment on the line being read starts, so -// that quoting a statement can stop before it. -func (l *Lexer) noteComment() { - if l.comments == nil { - l.comments = make(map[int]int) +// Spelling is the source a statement is spelled with: the input from first's +// own start to the end of last, so a comment the statement does not reach is +// never in it. Every line after the first moves left by the indentation first +// stands at, or by its own leading spaces where it has fewer, so nothing it +// spells is ever cut. A line a string literal runs into keeps its characters +// as they are, since those are what the string holds; literals are the string +// tokens the statement spans. A statement either token spells no source has +// no spelling. +func (l *Lexer) Spelling(first, last token.Token, literals []token.Token) string { + if first.Len == 0 || last.Len == 0 || first.Pos > last.Pos { + return "" } - l.comments[l.lineOffset] = l.column -} -// noteStringBreak records that a string literal runs past the end of the line -// being read, so that quoting a statement leaves the next line's own -// characters alone: they are the string's content, not the file's layout. -func (l *Lexer) noteStringBreak() { - if l.stringBreaks == nil { - l.stringBreaks = make(map[int]bool) + dedent := first.Column - 1 + spelled := make([]string, 0, 4) + for i, line := range spanLines(l.input, first.Pos, last.Pos+last.Len) { + text := line.text + if i > 0 && !inLiteral(literals, line.pos) { + text = text[min(dedent, len(text)-len(strings.TrimLeft(text, " "))):] + } + if !inLiteral(literals, line.end) { + text = strings.TrimRight(text, " \t") + } + spelled = append(spelled, text) } - l.stringBreaks[l.lineOffset] = true + return strings.Join(spelled, "\n") +} + +// spanLine is one line of a span: its text, and where in the input it starts +// and ends. A line a literal runs into starts inside one; a line a literal +// runs out of ends inside one. +type spanLine struct { + text string + pos int + end int } -// lines returns the source as its physical lines, each terminator the +// spanLines splits the input from pos to end into lines, each terminator the // language counts as one — LF, CRLF and CR alike, as LogicalRune reads them — // ending exactly one line. -func (l *Lexer) lines() []string { - if l.src == nil { - text := strings.ReplaceAll(strings.ReplaceAll(string(l.input), "\r\n", "\n"), "\r", "\n") - l.src = strings.Split(text, "\n") - } - return l.src -} - -// dedent is how far Text may move a span's lines left: the indentation of the -// line it starts on, or the least a line in the span has where that is less, -// as a table's hanging `:` header is. A line a string literal runs into holds -// content rather than layout, and a line its comment leaves blank holds -// nothing, so neither counts. The span's lines come with their comments -// already cut, since a comment may sit at any column and would otherwise -// measure as the whole statement's indentation. -func (l *Lexer) dedent(span [][]rune, startLine, startColumn int) int { - dedent := startColumn - 1 - for i, runes := range span { - if dedent == 0 { - break +func spanLines(input []rune, pos, end int) []spanLine { + lines := []spanLine{} + for start := pos; ; { + i := start + for i < end && input[i] != '\n' && input[i] != '\r' { + i++ } - line := string(runes) - if l.stringBreaks[startLine+i-1] || strings.TrimSpace(line) == "" { - continue + lines = append(lines, spanLine{text: string(input[start:i]), pos: start, end: i}) + if i >= end { + return lines } - dedent = min(dedent, len(line)-len(strings.TrimLeft(line, " "))) + _, start = LogicalRune(input, i) } - return dedent } -// Text is the source a statement is spelled with: the lines it spans, each cut -// before any comment that line ends with, moved left to the indentation of the -// line it starts on, and with trailing space dropped. A line a string literal -// runs into keeps its own characters, since they are what the string holds. -// Lines and columns are the ones a token carries, counted from one; a span -// naming no line of this input is empty. A comment is cut only on a line the -// lexer has already read. -func (l *Lexer) Text(startLine, startColumn, endLine int) string { - lines := l.lines() - if startLine < 1 || startColumn < 1 || startLine > endLine || endLine > len(lines) { - return "" - } - - span := make([][]rune, 0, endLine-startLine+1) - for n := startLine; n <= endLine; n++ { - runes := []rune(lines[n-1]) - if column, commented := l.comments[n]; commented { - runes = runes[:min(column-1, len(runes))] - } - span = append(span, runes) - } - - dedent := l.dedent(span, startLine, startColumn) - spelled := make([]string, len(span)) - for i, runes := range span { - if !l.stringBreaks[startLine+i-1] { - runes = runes[min(dedent, len(runes)):] - } - line := string(runes) - if !l.stringBreaks[startLine+i] { - line = strings.TrimRight(line, " \t") +// inLiteral reports whether pos falls inside one of the string literals, +// where the characters are the string's own rather than the file's layout. +func inLiteral(literals []token.Token, pos int) bool { + for _, lit := range literals { + if pos > lit.Pos && pos < lit.Pos+lit.Len { + return true } - spelled[i] = line } - return strings.Join(spelled, "\n") + return false } // tokenAt makes a token at column on the line being read. Len stays zero: @@ -397,7 +370,6 @@ func (l *Lexer) lex() (token.Token, *token.CompileError) { hadSpace := l.skipWhitespace() if l.curr == '#' { - l.noteComment() l.skipComment() } @@ -522,7 +494,6 @@ func (l *Lexer) nextLine() (column int, first rune, tab int) { case '\n': // a blank line l.skipWhitespace() case '#': // a comment line - l.noteComment() l.skipComment() default: return column, first, tab @@ -634,9 +605,6 @@ func (l *Lexer) readString(tok token.Token) (string, *token.CompileError) { } for l.curr != '"' && !l.atEOF() { - if l.curr == '\n' { - l.noteStringBreak() - } if l.curr == 0 { setError("NUL character is not allowed in string literals") l.readRune() diff --git a/lexer/lexer_test.go b/lexer/lexer_test.go index e6c79ad2..b2212385 100644 --- a/lexer/lexer_test.go +++ b/lexer/lexer_test.go @@ -1419,60 +1419,81 @@ func TestDecodeStringEscapePhysicalBreak(t *testing.T) { } } -// Text quotes a statement as its file spells it: lines dedented to the one it -// starts on, each cut before a comment, with LF, CRLF and CR all ending one -// line. A span naming no line of the input is empty. -func TestText(t *testing.T) { - const script = "a = 1 # one\nm = [\n # a row\n 2 3\n]\n" - const body = "r = G(x)\n m = [\n 2 3\n ]\n" - const str = "w = \"hello \n \nworld\"\n" - const bodyStr = "r = G(x)\n s = \"line one\nline two\"\n" - const hanging = "r = G(x)\n t = [\n : Name Score\n \"Ada\" 1\n ]\n" - const flushComment = "r = G(x)\n m = [\n# flush left\n 2 3\n ]\n" - const tabComment = "r = G(x)\n m = [\n\t# tabbed\n 2 3\n ]\n" +// spellAll quotes every token of src as one span, as a parser does for a +// statement: from the first token a source spells to the last, with the +// string literals between them. +func spellAll(t *testing.T, src string) string { + t.Helper() + l := New("spellAll", src) + var first, last token.Token + var literals []token.Token + for { + tok, err := l.NextToken() + if err != nil { + t.Fatalf("unexpected error at %d:%d: %v", tok.Line, tok.Column, err) + } + if tok.Type == token.EOF { + break + } + if tok.Len == 0 { + continue + } + if first.Len == 0 { + first = tok + } + last = tok + if tok.Type == token.STRING { + literals = append(literals, tok) + } + } + return l.Spelling(first, last, literals) +} + +// Spelling quotes a statement as its file spells it: from its first token to +// its last, so a comment it does not reach is never in it, with every later +// line moved left to where the first stands and a line a string literal runs +// through left as the string holds it. +func TestSpelling(t *testing.T) { cases := []struct { - name string - src string - startLine, startColumn, endLine int - want string + name string + src string + want string }{ - {"OneLineCutsItsComment", script, 1, 1, 1, "a = 1"}, - {"LinesKeepTheirShape", script, 2, 1, 5, "m = [\n\n 2 3\n]"}, - {"DedentedToItsFirstLine", body, 2, 5, 4, "m = [\n 2 3\n]"}, - {"StringContentKeepsItsSpaces", str, 1, 1, 3, "w = \"hello \n \nworld\""}, - {"StringContentIsNotMovedLeft", bodyStr, 2, 5, 3, "s = \"line one\nline two\""}, - {"HangingHeaderKeepsItsColon", hanging, 2, 5, 5, " t = [\n: Name Score\n \"Ada\" 1\n ]"}, - {"AFlushLeftCommentDoesNotHoldTheSpanBack", flushComment, 2, 5, 5, "m = [\n\n 2 3\n]"}, - {"ATabbedCommentDoesNotHoldTheSpanBack", tabComment, 2, 5, 5, "m = [\n\n 2 3\n]"}, - {"BeforeTheInput", script, 0, 1, 1, ""}, - {"PastTheInput", script, 1, 1, 99, ""}, - {"BeforeTheFirstColumn", script, 1, 0, 1, ""}, - {"Backwards", script, 3, 1, 2, ""}, + {"OneLineLeavesItsComment", "a = 1 # one\n", "a = 1"}, + {"LinesKeepTheirShape", "m = [\n 2 3\n]\n", "m = [\n 2 3\n]"}, + {"AnInteriorCommentStays", "m = [\n # a row\n 2 3\n]\n", "m = [\n # a row\n 2 3\n]"}, + {"StringContentKeepsItsSpaces", "w = \"hello \n \nworld\"\n", "w = \"hello \n \nworld\""}, + {"ADeeperLineKeepsItsShape", "long =\n a + 1\n", "long =\n a + 1"}, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { - l := New("TestText", tc.src) - for { - tok, _ := l.NextToken() - if tok.Type == token.EOF { - break - } - } - if got := l.Text(tc.startLine, tc.startColumn, tc.endLine); got != tc.want { - t.Fatalf("Text(%d, %d, %d) = %q, want %q", tc.startLine, tc.startColumn, tc.endLine, got, tc.want) + if got := spellAll(t, tc.src); got != tc.want { + t.Fatalf("Spelling = %q, want %q", got, tc.want) } }) } } -// Text reads a terminator the same however the file spells it, as the lexer -// itself does. -func TestTextLineEndings(t *testing.T) { - for name, src := range map[string]string{"LF": "a = 1\nb = 2\n", "CRLF": "a = 1\r\nb = 2\r\n", "CR": "a = 1\rb = 2\r"} { +// A statement either token spells no source has no spelling, so a caller that +// hands over a layout token gets nothing rather than a slice of the input. +func TestSpellingWantsSpelledTokens(t *testing.T) { + l := New("TestSpellingWantsSpelledTokens", "a = 1\n") + first, _ := l.NextToken() + if got := l.Spelling(first, token.Token{}, nil); got != "" { + t.Fatalf("Spelling with an unspelled last = %q, want %q", got, "") + } + if got := l.Spelling(token.Token{}, first, nil); got != "" { + t.Fatalf("Spelling with an unspelled first = %q, want %q", got, "") + } +} + +// Spelling reads a terminator the same however the file spells it, as the +// lexer itself does. +func TestSpellingLineEndings(t *testing.T) { + for name, src := range map[string]string{"LF": "m = [\n 2\n]\n", "CRLF": "m = [\r\n 2\r\n]\r\n", "CR": "m = [\r 2\r]\r"} { t.Run(name, func(t *testing.T) { - l := New("TestTextLineEndings", src) - if got, want := l.Text(1, 1, 2), "a = 1\nb = 2"; got != want { - t.Fatalf("Text = %q, want %q", got, want) + if got, want := spellAll(t, src), "m = [\n 2\n]"; got != want { + t.Fatalf("Spelling = %q, want %q", got, want) } }) } diff --git a/parser/parser.go b/parser/parser.go index d206759f..9c877b47 100644 --- a/parser/parser.go +++ b/parser/parser.go @@ -96,10 +96,12 @@ type StmtParser struct { l *lexer.Lexer errors []*token.CompileError - curToken token.Token - peekToken token.Token - stmtStart token.Token // the first token of the statement being parsed - savedTokens []token.Token // FIFO queue of synthetic tokens from operator splits or inserting a * in something like 9x + curToken token.Token + peekToken token.Token + stmtStart token.Token // the first token of the statement being parsed + stmtEnd token.Token // the last token of it a source spells + stmtLiterals []token.Token // the string literals it spans + savedTokens []token.Token // FIFO queue of synthetic tokens from operator splits or inserting a * in something like 9x prefixParseFns map[string]prefixParseFn infixParseFns map[string]infixParseFn @@ -178,6 +180,7 @@ func New(l *lexer.Lexer) *StmtParser { func (p *StmtParser) nextToken() { // always advance current token p.curToken = p.peekToken + p.noteSpelled(p.curToken) // get new peek token from queue or lexer if len(p.savedTokens) > 0 { @@ -421,11 +424,25 @@ func (p *StmtParser) ParseProgram() *ast.Program { return program } +// noteSpelled keeps what a statement's spelling needs of the token now +// current: the last one a source spells, since the layout token a statement +// ends on reaches past it, and the string literals it spans, whose characters +// are the string's own rather than the file's layout. +func (p *StmtParser) noteSpelled(tok token.Token) { + if tok.Len == 0 { + return + } + p.stmtEnd = tok + if tok.Type == token.STRING { + p.stmtLiterals = append(p.stmtLiterals, tok) + } +} + // spell gives stmt the source its file spells it with, from the token the -// statement started at to the one it ended on. A plan quotes that rather than -// the ast's own rendering, so what a reader sees is what they wrote. +// statement started at to the last one it spells. A plan quotes that rather +// than the ast's own rendering, so what a reader sees is what they wrote. func (p *StmtParser) spell(stmt ast.Statement) { - src := p.l.Text(p.stmtStart.Line, p.stmtStart.Column, p.curToken.Line) + src := p.l.Spelling(p.stmtStart, p.stmtEnd, p.stmtLiterals) switch s := stmt.(type) { case *ast.LetStatement: s.Src = src @@ -440,6 +457,9 @@ func (p *StmtParser) parseStatement() ast.Statement { } firstToken := p.curToken p.stmtStart = firstToken + p.stmtEnd = firstToken + p.stmtLiterals = p.stmtLiterals[:0] + p.noteSpelled(firstToken) p.blankIdents = nil // reset for new statement expList := p.parseExpList(prefixSplitNone, 0) // An expression that failed to parse is nil and has already reported its diff --git a/parser/scriptparser_test.go b/parser/scriptparser_test.go index 105a2770..384529dd 100644 --- a/parser/scriptparser_test.go +++ b/parser/scriptparser_test.go @@ -115,6 +115,7 @@ func TestSpellingReparses(t *testing.T) { "long =\n a + 1\n", "w = \"hello \n \n\t\nworld\"\n", "s = \"a\nb\"\n\"out: -s\"\n", + "u =\n# a comment the statement runs past\n 1 + 1\n", } for i, script := range scripts { t.Run(fmt.Sprintf("script%d", i), func(t *testing.T) { @@ -174,7 +175,7 @@ line two" spelled = append(spelled, inner.(*ast.LetStatement).Src) } } - require.Equal(t, []string{"t = x * 2", "s = \"line one\nline two\"", "u =\n\n x + 1", "r = t + 1"}, spelled) + require.Equal(t, []string{"t = x * 2", "s = \"line one\nline two\"", "u =\n# flush left\n x + 1", "r = t + 1"}, spelled) } func TestInvalidAssignment(t *testing.T) { From 20afc33fbd46e9f6cca139fb57138b5d1e99c30b Mon Sep 17 00:00:00 2001 From: Tejas Date: Tue, 24 Nov 2026 08:57:11 +0530 Subject: [PATCH 13/39] fix(lexer): start a shift where its spelling does, and move a span as one MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two reviews of the token-span rewrite found four faults, each reproduced. A shift operator was made after its run had been read, so `>>` carried the position of its second `>` and spelled `>`, and `>>>` spelled `>>`. It is made at its first rune now, which also puts its reported column there. The extent oracle covers the shifts, the comparisons, a float opening with a dot, and a table header, the other token the layout rules lex ahead. Clamping each line's indentation on its own moved a table's hanging `:` and its rows by different amounts, so the header stopped standing against them and the text no longer parsed. A span moves as one again: the margin is the least indentation its lines can all spare, the first line carries what it keeps, and a blank or comment-only line neither sets the margin nor loses more than it has — which is what let the per-line clamp in. Walking every literal for every line cost a statement quadratic time. Lines and literals are both in source order, so one forward pass settles each. On an 8,000-row table of strings: 118ms before, 5.5ms after. Spelling guarded a span too loosely for an exported function: a column before the first, a position outside the input, a length below zero or a reach past the end each slid past it into a panic. All of them, and both margin rules, are named cases now. A split operator kept neither half's runes. `√-x` left two tokens with no extent at all, which no plan reads today but a diagnostic would. Co-Authored-By: Claude Opus 5 --- lexer/lexer.go | 106 ++++++++++++++++++++++++++---------- lexer/lexer_test.go | 52 +++++++++++++++--- parser/parser.go | 10 +++- parser/scriptparser_test.go | 6 +- 4 files changed, 132 insertions(+), 42 deletions(-) diff --git a/lexer/lexer.go b/lexer/lexer.go index 5ebe1cef..1c44b3c5 100644 --- a/lexer/lexer.go +++ b/lexer/lexer.go @@ -94,39 +94,76 @@ func (l *Lexer) createToken(tokenType token.TokenType, literal string, hadSpace // Spelling is the source a statement is spelled with: the input from first's // own start to the end of last, so a comment the statement does not reach is -// never in it. Every line after the first moves left by the indentation first -// stands at, or by its own leading spaces where it has fewer, so nothing it -// spells is ever cut. A line a string literal runs into keeps its characters -// as they are, since those are what the string holds; literals are the string -// tokens the statement spans. A statement either token spells no source has -// no spelling. +// never in it. Its lines keep the shape the file gives them, moved left +// together by as much as all of them can spare, so a table's hanging header +// still stands against its rows. A line a string literal runs into keeps its +// characters as they are, since those are what the string holds; literals are +// the string tokens the statement spans, in source order. A statement either +// token spells no source, or whose span falls outside the input, has no +// spelling. func (l *Lexer) Spelling(first, last token.Token, literals []token.Token) string { - if first.Len == 0 || last.Len == 0 || first.Pos > last.Pos { + if first.Len <= 0 || last.Len <= 0 || first.Column < 1 || first.Pos < 0 || + first.Pos > last.Pos || last.Pos+last.Len > len(l.input) { return "" } - dedent := first.Column - 1 - spelled := make([]string, 0, 4) - for i, line := range spanLines(l.input, first.Pos, last.Pos+last.Len) { + lines := spanLines(l.input, first.Pos, last.Pos+last.Len) + markLiterals(lines, literals) + indent := first.Column - 1 + dedent := margin(lines, indent) + + spelled := make([]string, len(lines)) + for i, line := range lines { text := line.text - if i > 0 && !inLiteral(literals, line.pos) { - text = text[min(dedent, len(text)-len(strings.TrimLeft(text, " "))):] + switch { + case line.content: + case i == 0: + text = strings.Repeat(" ", indent-dedent) + text + default: + text = text[min(dedent, leading(text)):] } - if !inLiteral(literals, line.end) { + if !line.open { text = strings.TrimRight(text, " \t") } - spelled = append(spelled, text) + spelled[i] = text } return strings.Join(spelled, "\n") } -// spanLine is one line of a span: its text, and where in the input it starts -// and ends. A line a literal runs into starts inside one; a line a literal -// runs out of ends inside one. +// margin is how far a span's lines move left together: the indentation its +// first line stands at, or the least a later line of its own layout has where +// that is less, so nothing a line spells is ever cut. A line a literal runs +// into holds a string's characters, and a blank or comment-only line holds +// nothing of the statement, so neither sets the margin. +func margin(lines []spanLine, indent int) int { + for _, line := range lines[1:] { + if indent == 0 { + break + } + trimmed := strings.TrimLeft(line.text, " ") + if line.content || trimmed == "" || strings.HasPrefix(trimmed, "#") { + continue + } + indent = min(indent, len(line.text)-len(trimmed)) + } + return indent +} + +// leading counts the spaces a line opens with. +func leading(text string) int { + return len(text) - len(strings.TrimLeft(text, " ")) +} + +// spanLine is one line of a span: its text, where in the input it starts and +// ends, and what a string literal does to it. content says one runs into the +// line, so its characters are the string's; open says one runs out of it, so +// what it ends with is the string's too. type spanLine struct { - text string - pos int - end int + text string + pos int + end int + content bool + open bool } // spanLines splits the input from pos to end into lines, each terminator the @@ -147,15 +184,22 @@ func spanLines(input []rune, pos, end int) []spanLine { } } -// inLiteral reports whether pos falls inside one of the string literals, -// where the characters are the string's own rather than the file's layout. -func inLiteral(literals []token.Token, pos int) bool { - for _, lit := range literals { - if pos > lit.Pos && pos < lit.Pos+lit.Len { - return true +// markLiterals says of each line what the string literals do to it. Lines and +// literals are both in source order, so one pass over each settles every +// line: a literal that ends before a line starts is behind every line after +// it, and one that starts after a line ends is ahead of every line before it. +func markLiterals(lines []spanLine, literals []token.Token) { + at := 0 + for i := range lines { + for at < len(literals) && literals[at].Pos+literals[at].Len <= lines[i].pos { + at++ + } + for j := at; j < len(literals) && literals[j].Pos < lines[i].end; j++ { + lit, stop := literals[j].Pos, literals[j].Pos+literals[j].Len + lines[i].content = lines[i].content || (lines[i].pos > lit && lines[i].pos < stop) + lines[i].open = lines[i].open || (lines[i].end > lit && lines[i].end < stop) } } - return false } // tokenAt makes a token at column on the line being read. Len stays zero: @@ -432,12 +476,14 @@ func (l *Lexer) lex() (token.Token, *token.CompileError) { tok = l.createToken(token.GEQ, token.SYM_GEQ, hadSpace) l.readRune() } else if l.peekRune() == '>' { + // The token starts at the first '>', so it is made before the + // rest of the run is read: a token carries where its spelling + // starts, and its column is reported from there. + tok = l.createToken(token.OPERATOR, token.SYM_ASR, hadSpace) l.readRune() if l.peekRune() == '>' { - tok = l.createToken(token.OPERATOR, token.SYM_SHR, hadSpace) + tok.Literal = token.SYM_SHR l.readRune() - } else { - tok = l.createToken(token.OPERATOR, token.SYM_ASR, hadSpace) } } else { tok = l.createToken(token.GTR, token.SYM_GTR, hadSpace) diff --git a/lexer/lexer_test.go b/lexer/lexer_test.go index b2212385..8093d869 100644 --- a/lexer/lexer_test.go +++ b/lexer/lexer_test.go @@ -1474,16 +1474,50 @@ func TestSpelling(t *testing.T) { } } -// A statement either token spells no source has no spelling, so a caller that -// hands over a layout token gets nothing rather than a slice of the input. -func TestSpellingWantsSpelledTokens(t *testing.T) { - l := New("TestSpellingWantsSpelledTokens", "a = 1\n") +// A span Spelling cannot stand behind has no spelling, so a caller that hands +// over a layout token, a column before the first, or a reach past the input +// gets nothing rather than a slice of whatever lies there. +func TestSpellingWantsASpanItCanStandBehind(t *testing.T) { + l := New("TestSpellingWantsASpanItCanStandBehind", "a = 1\nb = 2\n") first, _ := l.NextToken() - if got := l.Spelling(first, token.Token{}, nil); got != "" { - t.Fatalf("Spelling with an unspelled last = %q, want %q", got, "") + last := first + for { + tok, _ := l.NextToken() + if tok.Type == token.EOF { + break + } + if tok.Len > 0 { + last = tok + } } - if got := l.Spelling(token.Token{}, first, nil); got != "" { - t.Fatalf("Spelling with an unspelled first = %q, want %q", got, "") + + past := last + past.Len = 99 + before := first + before.Column = 0 + negative := first + negative.Pos = -1 + backwards := first + backwards.Pos = last.Pos + 1 + + cases := []struct { + name string + first, last token.Token + }{ + {"AnUnspelledLast", first, token.Token{}}, + {"AnUnspelledFirst", token.Token{}, first}, + {"ANegativeLength", first, token.Token{Pos: 1, Len: -1}}, + {"AColumnBeforeTheFirst", before, last}, + {"APositionBeforeTheInput", negative, last}, + {"AReachPastTheInput", first, past}, + {"ASpanThatRunsBackwards", backwards, first}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + if got := l.Spelling(tc.first, tc.last, nil); got != "" { + t.Fatalf("Spelling = %q, want %q", got, "") + } + }) } } @@ -1503,7 +1537,7 @@ func TestSpellingLineEndings(t *testing.T) { // can quote any span of the input from its tokens alone. A layout token // spells nothing and says so with a zero length. func TestTokenExtents(t *testing.T) { - const src = "a = 5 # one\nm = [\n 2 3\n]\ns = \"x\ny\"\nimp = 5a\n" + const src = "a = 5 # one\nm = [\n 2 3\n]\ns = \"x\ny\"\nimp = 5a\nf = -8 >> 1 >>> 2 << 3\ng = a == b != c <= d >= e\nh = .5\nt = [\n : Name Score\n \"Ada\" 1\n]\n" l := New("TestTokenExtents", src) runes := []rune(src) for { diff --git a/parser/parser.go b/parser/parser.go index 9c877b47..708f666e 100644 --- a/parser/parser.go +++ b/parser/parser.go @@ -282,7 +282,9 @@ func (p *StmtParser) splitOperator(tok token.Token, opType OpType) []token.Token return []token.Token{tok} // No split needed } - // Split into matched part and remainder + // Split into matched part and remainder. Each piece keeps the runes of + // the run that spell it, so a token still says where its own source is. + matched := utf8.RuneCountInString(match) result := []token.Token{ { Type: token.OPERATOR, @@ -290,6 +292,8 @@ func (p *StmtParser) splitOperator(tok token.Token, opType OpType) []token.Token FileName: tok.FileName, Line: tok.Line, Column: tok.Column, + Pos: tok.Pos, + Len: min(matched, tok.Len), // Preserve source spacing so attached-prefix boundary checks still // work after an operator run is split into parseable pieces. HadSpace: tok.HadSpace, @@ -303,7 +307,9 @@ func (p *StmtParser) splitOperator(tok token.Token, opType OpType) []token.Token Literal: remainder, FileName: tok.FileName, Line: tok.Line, - Column: tok.Column + utf8.RuneCountInString(match), + Column: tok.Column + matched, + Pos: tok.Pos + matched, + Len: max(tok.Len-matched, 0), }) } diff --git a/parser/scriptparser_test.go b/parser/scriptparser_test.go index 384529dd..069b4304 100644 --- a/parser/scriptparser_test.go +++ b/parser/scriptparser_test.go @@ -158,6 +158,10 @@ line two" u = # flush left x + 1 + v = [ + : Name Score + "Ada" 1 + ] r = t + 1 ` l := lexer.New("TestStatementSpellingInBody", code) @@ -175,7 +179,7 @@ line two" spelled = append(spelled, inner.(*ast.LetStatement).Src) } } - require.Equal(t, []string{"t = x * 2", "s = \"line one\nline two\"", "u =\n# flush left\n x + 1", "r = t + 1"}, spelled) + require.Equal(t, []string{"t = x * 2", "s = \"line one\nline two\"", "u =\n# flush left\n x + 1", " v = [\n: Name Score\n \"Ada\" 1\n ]", "r = t + 1"}, spelled) } func TestInvalidAssignment(t *testing.T) { From 9b24ccfd0356cfa686285993f7c5ce3564c7e319 Mon Sep 17 00:00:00 2001 From: Tejas Date: Tue, 24 Nov 2026 09:23:20 +0530 Subject: [PATCH 14/39] fix(lexer): read past a tab when a line holds nothing of the statement MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit margin decided whether a line was blank or a comment after trimming spaces alone, and Pluto allows a tab on either. So a tab-indented comment and a line of one tab each counted as a line of the statement with no indentation at all, dragging the margin to nothing and leaving the whole statement four columns right of where it belongs. Both shapes compile without an error; both are reported. This is the second time that pair has broken, and the second time a test that pinned it went out with a rewrite rather than with a decision. TestSpellingMovesASpanAsOne quotes an indented span the way a body's statement is quoted, so the tabbed comment, the tab-only line, the hanging header, a flush-left comment and two literals on one line are all pinned in the lexer rather than only through the parser. Spelling measured the reach past its last token by adding to its start, which a length a caller invented could carry past what an int holds. It compares against what is left of the input instead. The pieces a split operator leaves had no test: putting the old code back passed the whole parser suite. An ast-level case reads `√-x` and asks each piece for the runes it spells. §12 describes the common margin, which has replaced the per-line clamp since 20afc33 but was still written as one. Co-Authored-By: Claude Opus 5 --- docs/Pluto IR Plan.md | 10 ++++--- lexer/lexer.go | 13 ++++++--- lexer/lexer_test.go | 58 +++++++++++++++++++++++++++++++++++++ parser/scriptparser_test.go | 23 +++++++++++++++ 4 files changed, 96 insertions(+), 8 deletions(-) diff --git a/docs/Pluto IR Plan.md b/docs/Pluto IR Plan.md index f4357cba..1a709402 100644 --- a/docs/Pluto IR Plan.md +++ b/docs/Pluto IR Plan.md @@ -742,10 +742,12 @@ rather than an operand: the label stands alone and the statement's own lines sit one level in, so a block literal reads as it is laid out (decided 2026-11-23). What it renders is the file's own text, from the statement's first token to its last: a comment the statement does not reach is never in -it, while one between two of its own tokens is. Every line after the first -moves left to where the first stands, or by its own leading spaces where it -has fewer, so nothing a line spells is ever cut, and a line a string literal -runs through keeps the characters the string holds. So the parens the ast adds +it, while one between two of its own tokens is. The lines move left together, +by the least indentation they can all spare, so a table's header still hangs +where it stood against its rows; a line holding nothing of the statement — +blank, or a comment at any indentation — neither sets that margin nor loses +more than it has, and a line a string literal runs through keeps the +characters the string holds. So the parens the ast adds to spell out its own nesting are absent (`d = Twice(d) + 1`, not `d = (Twice(d) + 1)`), and an implicit multiplication reads as it was typed (`imp = 5a`). Every statement a plan is diff --git a/lexer/lexer.go b/lexer/lexer.go index 1c44b3c5..419727f7 100644 --- a/lexer/lexer.go +++ b/lexer/lexer.go @@ -102,8 +102,11 @@ func (l *Lexer) createToken(tokenType token.TokenType, literal string, hadSpace // token spells no source, or whose span falls outside the input, has no // spelling. func (l *Lexer) Spelling(first, last token.Token, literals []token.Token) string { + // The reach past last is measured against what is left of the input + // rather than added to its start, so a length a caller invented cannot + // carry the sum past what an int holds. if first.Len <= 0 || last.Len <= 0 || first.Column < 1 || first.Pos < 0 || - first.Pos > last.Pos || last.Pos+last.Len > len(l.input) { + first.Pos > last.Pos || last.Pos >= len(l.input) || last.Len > len(l.input)-last.Pos { return "" } @@ -140,11 +143,13 @@ func margin(lines []spanLine, indent int) int { if indent == 0 { break } - trimmed := strings.TrimLeft(line.text, " ") - if line.content || trimmed == "" || strings.HasPrefix(trimmed, "#") { + // A blank or comment line may be indented with tabs, which no line + // of the statement's own may be, so what it holds is read past both. + held := strings.TrimLeft(line.text, " \t") + if line.content || held == "" || strings.HasPrefix(held, "#") { continue } - indent = min(indent, len(line.text)-len(trimmed)) + indent = min(indent, leading(line.text)) } return indent } diff --git a/lexer/lexer_test.go b/lexer/lexer_test.go index 8093d869..2c1ff62d 100644 --- a/lexer/lexer_test.go +++ b/lexer/lexer_test.go @@ -1449,6 +1449,61 @@ func spellAll(t *testing.T, src string) string { return l.Spelling(first, last, literals) } +// spellFrom quotes the tokens of src from the first one on line from, as a +// parser does for a statement a function body indents. +func spellFrom(t *testing.T, src string, from int) string { + t.Helper() + l := New("spellFrom", src) + var first, last token.Token + var literals []token.Token + for { + tok, err := l.NextToken() + if err != nil { + t.Fatalf("unexpected error at %d:%d: %v", tok.Line, tok.Column, err) + } + if tok.Type == token.EOF { + break + } + if tok.Len == 0 || tok.Line < from { + continue + } + if first.Len == 0 { + first = tok + } + last = tok + if tok.Type == token.STRING { + literals = append(literals, tok) + } + } + return l.Spelling(first, last, literals) +} + +// A span an indented statement makes moves left as one, by as much as all of +// its lines can spare. A line holding nothing of the statement — blank or a +// comment, however it is indented — neither sets that margin nor loses more +// than it has. +func TestSpellingMovesASpanAsOne(t *testing.T) { + cases := []struct { + name string + src string + want string + }{ + {"ABodyComesBackToItsOwnLevel", "r = G(x)\n m = [\n 2 3\n ]\n", "m = [\n 2 3\n]"}, + {"AFlushLeftCommentHoldsNothingBack", "r = G(x)\n m = [\n# flush left\n 2 3\n ]\n", "m = [\n# flush left\n 2 3\n]"}, + {"ATabbedCommentHoldsNothingBack", "r = G(x)\n m = [\n\t# tabbed\n 2 3\n ]\n", "m = [\n\t# tabbed\n 2 3\n]"}, + {"ATabOnlyLineHoldsNothingBack", "r = G(x)\n m = [\n\t\n 2 3\n ]\n", "m = [\n\n 2 3\n]"}, + {"AHangingHeaderStandsAgainstItsRows", "r = G(x)\n t = [\n : Name Score\n \"Ada\" 1\n ]\n", " t = [\n: Name Score\n \"Ada\" 1\n ]"}, + {"TwoLiteralsOnOneLine", "r = G(x)\n s = \"a\" ⊕ \"b\n c\"\n", "s = \"a\" ⊕ \"b\n c\""}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + if got := spellFrom(t, tc.src, 2); got != tc.want { + t.Fatalf("Spelling = %q, want %q", got, tc.want) + } + }) + } +} + // Spelling quotes a statement as its file spells it: from its first token to // its last, so a comment it does not reach is never in it, with every later // line moved left to where the first stands and a line a string literal runs @@ -1550,6 +1605,9 @@ func TestTokenExtents(t *testing.T) { } switch tok.Type { case token.INDENT, token.DEINDENT, token.NEWLINE: + if tok.Len != 0 { + t.Fatalf("layout token %q at %d:%d spells %d runes, want none", tok.Literal, tok.Line, tok.Column, tok.Len) + } continue } if tok.Len <= 0 { diff --git a/parser/scriptparser_test.go b/parser/scriptparser_test.go index 069b4304..685c7a18 100644 --- a/parser/scriptparser_test.go +++ b/parser/scriptparser_test.go @@ -103,6 +103,29 @@ world" } } +// A run of operator characters the parser splits gives each piece the runes +// of the run that spell it, so a token still says where its own source is. +func TestSplitOperatorKeepsItsRunes(t *testing.T) { + const script = "x = 3\ny = √-x\n" + sp := NewScriptParser(lexer.New("TestSplitOperatorKeepsItsRunes", script)) + program := sp.Parse() + require.Empty(t, sp.Errors(), "unexpected parse errors: %v", sp.Errors()) + require.Len(t, program.Statements, 2) + + root, isRoot := program.Statements[1].(*ast.LetStatement).Value[0].(*ast.PrefixExpression) + require.True(t, isRoot, "expected a prefix expression") + inner, isInner := root.Right.(*ast.PrefixExpression) + require.True(t, isInner, "expected a prefix expression under it") + + runes := []rune(script) + for _, op := range []*ast.PrefixExpression{root, inner} { + tok := op.Tok() + require.Equal(t, tok.Literal, string(runes[tok.Pos:tok.Pos+tok.Len]), + "operator %q spells %q", tok.Literal, string(runes[tok.Pos:tok.Pos+tok.Len])) + } + require.Equal(t, root.Tok().Pos+root.Tok().Len, inner.Tok().Pos, "the pieces must follow one another") +} + // A statement's spelling holds everything the statement does, so parsing it // on its own gives the same statement back. That catches a span that dropped // or added a character where no golden names it. From 700cae19b4379a7748b6a7f1516152dad906579a Mon Sep 17 00:00:00 2001 From: Tejas Date: Tue, 24 Nov 2026 10:39:38 +0530 Subject: [PATCH 15/39] refactor(parser): let parseStatement own a statement's capture MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Recording a statement's tokens was started in one place, fed in another, and finished by two callers that each had to remember it. A path that parses something else entirely — a code file's declarations, which no plan is built from — fed the recording without ever starting or finishing it, so every string token in such a file was kept for as long as the parser lived. A file of 10,000 string constants held 10,000 of them, about 870 KiB; a script held none, since every statement there resets. parseStatement starts the recording and, on a named return, hands the statement its spelling before it goes. noteSpelled keeps nothing while no statement is being parsed, so the declaration path now keeps nothing at all — len and cap both zero where they were 10,000 and 11,161 — and the two statement loops lose a responsibility that was never theirs. A statement that failed to parse is no longer spelled, where the loops used to skip it. Co-Authored-By: Claude Opus 5 --- parser/codeparser_test.go | 14 ++++++++++++++ parser/parser.go | 22 ++++++++++++++++------ 2 files changed, 30 insertions(+), 6 deletions(-) diff --git a/parser/codeparser_test.go b/parser/codeparser_test.go index 47f9ebf2..41ffccd2 100644 --- a/parser/codeparser_test.go +++ b/parser/codeparser_test.go @@ -721,3 +721,17 @@ p = Person require.IsType(t, &ast.StructStatement{}, code.Statements[0]) require.IsType(t, &ast.StructStatement{}, code.Statements[1]) } + +// A declaration is no statement a plan is built from, so parsing one keeps +// none of its tokens: the recording runs for as long as parseStatement does +// and no longer, where it once grew for the parser's whole life. +func TestCodeDeclarationsKeepNoTokens(t *testing.T) { + var src strings.Builder + for i := 0; i < 100; i++ { + src.WriteString("k = \"v\"\n") + } + cp := NewCodeParser(lexer.New("TestCodeDeclarationsKeepNoTokens", src.String())) + cp.Parse() + require.Empty(t, cp.Errors(), "unexpected parse errors: %v", cp.Errors()) + require.Empty(t, cp.p.stmtLiterals, "a declaration's tokens must not be kept") +} diff --git a/parser/parser.go b/parser/parser.go index 708f666e..4fffe51d 100644 --- a/parser/parser.go +++ b/parser/parser.go @@ -98,6 +98,7 @@ type StmtParser struct { curToken token.Token peekToken token.Token + spelling bool // a statement is being parsed, so its tokens are kept stmtStart token.Token // the first token of the statement being parsed stmtEnd token.Token // the last token of it a source spells stmtLiterals []token.Token // the string literals it spans @@ -419,7 +420,6 @@ func (p *StmtParser) ParseProgram() *ast.Program { program.Statements = []ast.Statement{} for !p.curTokenIs(token.EOF) { if stmt := p.parseStatement(); stmt != nil { - p.spell(stmt) program.Statements = append(program.Statements, stmt) } else { p.skipLine() @@ -435,7 +435,7 @@ func (p *StmtParser) ParseProgram() *ast.Program { // ends on reaches past it, and the string literals it spans, whose characters // are the string's own rather than the file's layout. func (p *StmtParser) noteSpelled(tok token.Token) { - if tok.Len == 0 { + if !p.spelling || tok.Len == 0 { return } p.stmtEnd = tok @@ -445,9 +445,15 @@ func (p *StmtParser) noteSpelled(tok token.Token) { } // spell gives stmt the source its file spells it with, from the token the -// statement started at to the last one it spells. A plan quotes that rather -// than the ast's own rendering, so what a reader sees is what they wrote. +// statement started at to the last one it spells, and closes the recording +// noteSpelled does. A plan quotes that rather than the ast's own rendering, +// so what a reader sees is what they wrote. func (p *StmtParser) spell(stmt ast.Statement) { + p.spelling = false + if stmt == nil { + return + } + src := p.l.Spelling(p.stmtStart, p.stmtEnd, p.stmtLiterals) switch s := stmt.(type) { case *ast.LetStatement: @@ -457,15 +463,20 @@ func (p *StmtParser) spell(stmt ast.Statement) { } } -func (p *StmtParser) parseStatement() ast.Statement { +// parseStatement parses one statement and gives it the source its file +// spells it with. The recording runs for exactly as long as this does, so a +// caller that parses a declaration of its own keeps none of its tokens. +func (p *StmtParser) parseStatement() (stmt ast.Statement) { if p.skipIndented() { return nil } firstToken := p.curToken + p.spelling = true p.stmtStart = firstToken p.stmtEnd = firstToken p.stmtLiterals = p.stmtLiterals[:0] p.noteSpelled(firstToken) + defer func() { p.spell(stmt) }() p.blankIdents = nil // reset for new statement expList := p.parseExpList(prefixSplitNone, 0) // An expression that failed to parse is nil and has already reported its @@ -1717,7 +1728,6 @@ func (p *StmtParser) parseBlockStatement() *ast.BlockStatement { for !p.curTokenIs(token.DEINDENT) && !p.curTokenIs(token.EOF) { if stmt := p.parseStatement(); stmt != nil { - p.spell(stmt) block.Statements = append(block.Statements, stmt) } else { p.skipLine() From 82ad719ce4e44946644acf3c14df7b7b6c1723fd Mon Sep 17 00:00:00 2001 From: Tejas Date: Tue, 24 Nov 2026 10:57:49 +0530 Subject: [PATCH 16/39] test(parser): ask the capture buffer what it still holds The retention test asked a parser that had never recorded anything, and asked it for a length. So it passed with the close removed, and it would pass again with a buffer emptied but kept: a `.pt` file holding a function and then string constants would retain them all and nothing would say so. Each case now puts a function first, so the recording has been on and has to have been closed, and asks for the buffer's capacity. One body parses and one does not, since a statement that fails takes its own way out of parseStatement: with the close removed both cases fail, and with it moved below the nil return only the failing body does. The let inside parseStatement no longer shares the name of the statement that function returns. A nil *ast.LetStatement is not a nil ast.Statement, so it has to be named and tested rather than returned straight through, but naming it after the return meant a reader had to work out which one the deferred spelling reads. Co-Authored-By: Claude Opus 5 --- parser/codeparser_test.go | 33 +++++++++++++++++++++++++-------- parser/parser.go | 8 ++++++-- 2 files changed, 31 insertions(+), 10 deletions(-) diff --git a/parser/codeparser_test.go b/parser/codeparser_test.go index 41ffccd2..b5e7a898 100644 --- a/parser/codeparser_test.go +++ b/parser/codeparser_test.go @@ -724,14 +724,31 @@ p = Person // A declaration is no statement a plan is built from, so parsing one keeps // none of its tokens: the recording runs for as long as parseStatement does -// and no longer, where it once grew for the parser's whole life. +// and no longer, where it once grew for the parser's whole life. Each case +// puts a function first, so the recording has been on and has to have been +// closed, and asks for the buffer's capacity rather than its length, since +// emptying a slice leaves what it allocated behind. A statement that fails +// to parse takes its own way out of parseStatement and closes the recording +// just the same. func TestCodeDeclarationsKeepNoTokens(t *testing.T) { - var src strings.Builder - for i := 0; i < 100; i++ { - src.WriteString("k = \"v\"\n") + cases := []struct { + name string + code string + parse bool + }{ + {"AfterABodyThatParsed", "r = F(x)\n r = x\nk = \"decl\"\n", true}, + {"AfterABodyThatDidNot", "r = F(x)\n 1 = x\nk = \"decl\"\n", false}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + cp := NewCodeParser(lexer.New(tc.name, tc.code)) + cp.Parse() + if tc.parse { + require.Empty(t, cp.Errors(), "unexpected parse errors: %v", cp.Errors()) + } else { + require.NotEmpty(t, cp.Errors(), "expected the body to fail to parse") + } + require.Zero(t, cap(cp.p.stmtLiterals), "a declaration must leave no capture buffer") + }) } - cp := NewCodeParser(lexer.New("TestCodeDeclarationsKeepNoTokens", src.String())) - cp.Parse() - require.Empty(t, cp.Errors(), "unexpected parse errors: %v", cp.Errors()) - require.Empty(t, cp.p.stmtLiterals, "a declaration's tokens must not be kept") } diff --git a/parser/parser.go b/parser/parser.go index 4fffe51d..172654d8 100644 --- a/parser/parser.go +++ b/parser/parser.go @@ -513,8 +513,12 @@ func (p *StmtParser) parseStatement() (stmt ast.Statement) { } p.checkNoDuplicates(identList) - if stmt := p.parseLetStatement(identList); stmt != nil { - return stmt + // A nil *ast.LetStatement is not a nil ast.Statement, so the let is named + // and tested rather than returned straight through. It is not named stmt: + // this function returns one, and nothing should have to ask which the + // deferred spelling reads. + if let := p.parseLetStatement(identList); let != nil { + return let } return nil } From 71f4dcac657f329d0047e016795d3afaa3f23f6f Mon Sep 17 00:00:00 2001 From: Tejas Date: Tue, 24 Nov 2026 11:20:08 +0530 Subject: [PATCH 17/39] refactor(lexer): state Spelling's span as a precondition Spelling opened with seven clauses on its two tokens, and not one of them can hold. The parser is its only caller, and it hands over tokens this lexer made, taken after skipIndented so both spell source of their own, in the order it read them. A length above zero, a position inside the input, a column from one and a first at or before a last are what a token the lexer produced already is. They came in as a review asked the exported function to defend itself, and a second asked the arithmetic in that defence to be overflow-safe. Both requests were right about the check they were looking at; neither asked whether a check belonged there. Returning "" for a span a caller invented is also the wrong answer to it: an empty source is the state validateHead calls a compiler bug, so the check turned one bug into another, reported further from where it was made. The span is the doc's precondition now, and 47 lines of tests for the answers it used to give are gone with it. Co-Authored-By: Claude Opus 5 --- lexer/lexer.go | 15 ++++----------- lexer/lexer_test.go | 47 --------------------------------------------- 2 files changed, 4 insertions(+), 58 deletions(-) diff --git a/lexer/lexer.go b/lexer/lexer.go index 419727f7..faa8c710 100644 --- a/lexer/lexer.go +++ b/lexer/lexer.go @@ -98,18 +98,11 @@ func (l *Lexer) createToken(tokenType token.TokenType, literal string, hadSpace // together by as much as all of them can spare, so a table's hanging header // still stands against its rows. A line a string literal runs into keeps its // characters as they are, since those are what the string holds; literals are -// the string tokens the statement spans, in source order. A statement either -// token spells no source, or whose span falls outside the input, has no -// spelling. +// the string tokens the statement spans, in source order. first and last are +// tokens this lexer produced, each spelling source of its own, first at or +// before last: no other pair names a span of this input, so a caller that +// hands one over has a bug that checking here would only move. func (l *Lexer) Spelling(first, last token.Token, literals []token.Token) string { - // The reach past last is measured against what is left of the input - // rather than added to its start, so a length a caller invented cannot - // carry the sum past what an int holds. - if first.Len <= 0 || last.Len <= 0 || first.Column < 1 || first.Pos < 0 || - first.Pos > last.Pos || last.Pos >= len(l.input) || last.Len > len(l.input)-last.Pos { - return "" - } - lines := spanLines(l.input, first.Pos, last.Pos+last.Len) markLiterals(lines, literals) indent := first.Column - 1 diff --git a/lexer/lexer_test.go b/lexer/lexer_test.go index 2c1ff62d..c9f875da 100644 --- a/lexer/lexer_test.go +++ b/lexer/lexer_test.go @@ -1529,53 +1529,6 @@ func TestSpelling(t *testing.T) { } } -// A span Spelling cannot stand behind has no spelling, so a caller that hands -// over a layout token, a column before the first, or a reach past the input -// gets nothing rather than a slice of whatever lies there. -func TestSpellingWantsASpanItCanStandBehind(t *testing.T) { - l := New("TestSpellingWantsASpanItCanStandBehind", "a = 1\nb = 2\n") - first, _ := l.NextToken() - last := first - for { - tok, _ := l.NextToken() - if tok.Type == token.EOF { - break - } - if tok.Len > 0 { - last = tok - } - } - - past := last - past.Len = 99 - before := first - before.Column = 0 - negative := first - negative.Pos = -1 - backwards := first - backwards.Pos = last.Pos + 1 - - cases := []struct { - name string - first, last token.Token - }{ - {"AnUnspelledLast", first, token.Token{}}, - {"AnUnspelledFirst", token.Token{}, first}, - {"ANegativeLength", first, token.Token{Pos: 1, Len: -1}}, - {"AColumnBeforeTheFirst", before, last}, - {"APositionBeforeTheInput", negative, last}, - {"AReachPastTheInput", first, past}, - {"ASpanThatRunsBackwards", backwards, first}, - } - for _, tc := range cases { - t.Run(tc.name, func(t *testing.T) { - if got := l.Spelling(tc.first, tc.last, nil); got != "" { - t.Fatalf("Spelling = %q, want %q", got, "") - } - }) - } -} - // Spelling reads a terminator the same however the file spells it, as the // lexer itself does. func TestSpellingLineEndings(t *testing.T) { From 7df48126367a99db2c4e6217439ad7d46e1ea2ed Mon Sep 17 00:00:00 2001 From: Tejas Date: Tue, 24 Nov 2026 11:44:38 +0530 Subject: [PATCH 18/39] fix(parser): take both ends of a span from what a source spells MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The precondition 71f4dca wrote down was not true yet. parseStatement took the token it first saw as the span's start, and error recovery can put a token that spells nothing there: an indent of tabs is reported and lexed as a token of its own, the expression parser steps over it, and the statement after it was then quoted from the tab. `\tx = 1` spelled "\tx = 1" rather than "x = 1". It panicked at neither end, since Spelling reads first.Pos and not first.Len, which is why the guard it replaced never caught this either — it answered "" instead, one wrong spelling for another. noteSpelled already took the last token a source spells, because the layout token a statement ends on reaches past it. It takes the first the same way now, so one rule gives Spelling both ends and parseStatement states no span of its own. Co-Authored-By: Claude Opus 5 --- parser/parser.go | 15 ++++++++++----- parser/scriptparser_test.go | 12 ++++++++++++ 2 files changed, 22 insertions(+), 5 deletions(-) diff --git a/parser/parser.go b/parser/parser.go index 172654d8..0dd7d815 100644 --- a/parser/parser.go +++ b/parser/parser.go @@ -431,13 +431,18 @@ func (p *StmtParser) ParseProgram() *ast.Program { } // noteSpelled keeps what a statement's spelling needs of the token now -// current: the last one a source spells, since the layout token a statement -// ends on reaches past it, and the string literals it spans, whose characters -// are the string's own rather than the file's layout. +// current: the first and last tokens a source spells, and the string literals +// between them, whose characters are the string's own rather than the file's +// layout. Both ends are taken from what a source spells, so neither the +// layout token a statement ends on nor the illegal one a recovered statement +// starts after can reach past it. func (p *StmtParser) noteSpelled(tok token.Token) { if !p.spelling || tok.Len == 0 { return } + if p.stmtStart.Len == 0 { + p.stmtStart = tok + } p.stmtEnd = tok if tok.Type == token.STRING { p.stmtLiterals = append(p.stmtLiterals, tok) @@ -472,8 +477,8 @@ func (p *StmtParser) parseStatement() (stmt ast.Statement) { } firstToken := p.curToken p.spelling = true - p.stmtStart = firstToken - p.stmtEnd = firstToken + p.stmtStart = token.Token{} + p.stmtEnd = token.Token{} p.stmtLiterals = p.stmtLiterals[:0] p.noteSpelled(firstToken) defer func() { p.spell(stmt) }() diff --git a/parser/scriptparser_test.go b/parser/scriptparser_test.go index 685c7a18..ad64811b 100644 --- a/parser/scriptparser_test.go +++ b/parser/scriptparser_test.go @@ -103,6 +103,18 @@ world" } } +// A statement the parser recovers is spelled from the first token a source +// spells, not from whatever stood before it. An indent of tabs is reported +// and lexed as a token of its own that spells nothing, and the statement that +// follows it is still quoted as it was written. +func TestRecoveredStatementSpellsWhatItHas(t *testing.T) { + sp := NewScriptParser(lexer.New("TestRecoveredStatementSpellsWhatItHas", "\tx = 1\nx\n")) + program := sp.Parse() + require.NotEmpty(t, sp.Errors(), "expected the tab indent to be reported") + require.Len(t, program.Statements, 2) + require.Equal(t, "x = 1", program.Statements[0].(*ast.LetStatement).Src) +} + // A run of operator characters the parser splits gives each piece the runes // of the run that spell it, so a token still says where its own source is. func TestSplitOperatorKeepsItsRunes(t *testing.T) { From d7200ec74a8d05f69824299b2cd44d170bbbb30d Mon Sep 17 00:00:00 2001 From: Tejas Date: Tue, 24 Nov 2026 12:48:16 +0530 Subject: [PATCH 19/39] refactor(lexer): keep a line's offsets inside the pass that needs them MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit spanLine carried where each line began and ended, and nothing read those once the literals had been marked: the margin and the emitting both go by a line's text and the two bits. They were scaffolding for a second pass over data the first had just walked. Splitting the span and marking it are one pass now, so the offsets never leave it and the type is the three things its readers want. The ordering that makes one cursor enough — lines read in source order, literals given in it — is a loop invariant rather than a promise between two functions. Six lines shorter, and no behaviour: the tabs, the hanging header, two literals on one line and every line ending still answer as they did. Co-Authored-By: Claude Opus 5 --- lexer/lexer.go | 54 ++++++++++++++++++++++---------------------------- 1 file changed, 24 insertions(+), 30 deletions(-) diff --git a/lexer/lexer.go b/lexer/lexer.go index faa8c710..501aa56d 100644 --- a/lexer/lexer.go +++ b/lexer/lexer.go @@ -103,8 +103,7 @@ func (l *Lexer) createToken(tokenType token.TokenType, literal string, hadSpace // before last: no other pair names a span of this input, so a caller that // hands one over has a bug that checking here would only move. func (l *Lexer) Spelling(first, last token.Token, literals []token.Token) string { - lines := spanLines(l.input, first.Pos, last.Pos+last.Len) - markLiterals(lines, literals) + lines := spanLines(l.input, first.Pos, last.Pos+last.Len, literals) indent := first.Column - 1 dedent := margin(lines, indent) @@ -152,51 +151,46 @@ func leading(text string) int { return len(text) - len(strings.TrimLeft(text, " ")) } -// spanLine is one line of a span: its text, where in the input it starts and -// ends, and what a string literal does to it. content says one runs into the -// line, so its characters are the string's; open says one runs out of it, so -// what it ends with is the string's too. +// spanLine is one line of a span: its text, and what a string literal does to +// it. content says one runs into the line, so its characters are the +// string's; open says one runs out of it, so what it ends with is too. Where +// the line sits in the input is what decides those, and is wanted for nothing +// else, so it stays inside spanLines. type spanLine struct { text string - pos int - end int content bool open bool } -// spanLines splits the input from pos to end into lines, each terminator the -// language counts as one — LF, CRLF and CR alike, as LogicalRune reads them — -// ending exactly one line. -func spanLines(input []rune, pos, end int) []spanLine { +// spanLines splits the input from pos to end into lines — each terminator the +// language counts as one, LF, CRLF and CR alike, as LogicalRune reads them — +// and says of each what the string literals do to it. It reads the lines in +// source order and the literals arrive in it, so one cursor settles them all: +// a literal that ends before a line starts is behind every line after it. +func spanLines(input []rune, pos, end int, literals []token.Token) []spanLine { lines := []spanLine{} + at := 0 for start := pos; ; { i := start for i < end && input[i] != '\n' && input[i] != '\r' { i++ } - lines = append(lines, spanLine{text: string(input[start:i]), pos: start, end: i}) - if i >= end { - return lines - } - _, start = LogicalRune(input, i) - } -} -// markLiterals says of each line what the string literals do to it. Lines and -// literals are both in source order, so one pass over each settles every -// line: a literal that ends before a line starts is behind every line after -// it, and one that starts after a line ends is ahead of every line before it. -func markLiterals(lines []spanLine, literals []token.Token) { - at := 0 - for i := range lines { - for at < len(literals) && literals[at].Pos+literals[at].Len <= lines[i].pos { + line := spanLine{text: string(input[start:i])} + for at < len(literals) && literals[at].Pos+literals[at].Len <= start { at++ } - for j := at; j < len(literals) && literals[j].Pos < lines[i].end; j++ { + for j := at; j < len(literals) && literals[j].Pos < i; j++ { lit, stop := literals[j].Pos, literals[j].Pos+literals[j].Len - lines[i].content = lines[i].content || (lines[i].pos > lit && lines[i].pos < stop) - lines[i].open = lines[i].open || (lines[i].end > lit && lines[i].end < stop) + line.content = line.content || (start > lit && start < stop) + line.open = line.open || (i > lit && i < stop) + } + lines = append(lines, line) + + if i >= end { + return lines } + _, start = LogicalRune(input, i) } } From e249d6703b9b09cf10967f59b67598ec8a5e90ff Mon Sep 17 00:00:00 2001 From: Tejas Date: Tue, 24 Nov 2026 13:20:31 +0530 Subject: [PATCH 20/39] docs(lexer): name a line's bits after the question they answer content and open said nothing about what they held. They answer whether a string literal is open at a line's start and at its end, which is the whole reason either exists: a line that begins inside a literal opens with the string's own characters, so moving it left would take them, and one that ends inside a literal ends with them, so trimming it would. A middle line of a literal of several lines does both. beginsInString and endsInString say that, and the two rules they guard read as the rules they are. Co-Authored-By: Claude Opus 5 --- lexer/lexer.go | 30 ++++++++++++++++-------------- 1 file changed, 16 insertions(+), 14 deletions(-) diff --git a/lexer/lexer.go b/lexer/lexer.go index 501aa56d..8f674785 100644 --- a/lexer/lexer.go +++ b/lexer/lexer.go @@ -111,13 +111,13 @@ func (l *Lexer) Spelling(first, last token.Token, literals []token.Token) string for i, line := range lines { text := line.text switch { - case line.content: + case line.beginsInString: case i == 0: text = strings.Repeat(" ", indent-dedent) + text default: text = text[min(dedent, leading(text)):] } - if !line.open { + if !line.endsInString { text = strings.TrimRight(text, " \t") } spelled[i] = text @@ -128,7 +128,7 @@ func (l *Lexer) Spelling(first, last token.Token, literals []token.Token) string // margin is how far a span's lines move left together: the indentation its // first line stands at, or the least a later line of its own layout has where // that is less, so nothing a line spells is ever cut. A line a literal runs -// into holds a string's characters, and a blank or comment-only line holds +// begins inside a string holds its characters, and a blank or comment-only line holds // nothing of the statement, so neither sets the margin. func margin(lines []spanLine, indent int) int { for _, line := range lines[1:] { @@ -138,7 +138,7 @@ func margin(lines []spanLine, indent int) int { // A blank or comment line may be indented with tabs, which no line // of the statement's own may be, so what it holds is read past both. held := strings.TrimLeft(line.text, " \t") - if line.content || held == "" || strings.HasPrefix(held, "#") { + if line.beginsInString || held == "" || strings.HasPrefix(held, "#") { continue } indent = min(indent, leading(line.text)) @@ -151,15 +151,17 @@ func leading(text string) int { return len(text) - len(strings.TrimLeft(text, " ")) } -// spanLine is one line of a span: its text, and what a string literal does to -// it. content says one runs into the line, so its characters are the -// string's; open says one runs out of it, so what it ends with is too. Where -// the line sits in the input is what decides those, and is wanted for nothing -// else, so it stays inside spanLines. +// spanLine is one line of a span: its text, and whether a string literal is +// open at either end of it. A line that begins inside one opens with the +// string's own characters, so moving it left would take them; a line that +// ends inside one ends with them, so trimming it would. A middle line of a +// literal of several lines does both. Where the line sits in the input is +// what decides these, and is wanted for nothing else, so it stays inside +// spanLines. type spanLine struct { - text string - content bool - open bool + text string + beginsInString bool + endsInString bool } // spanLines splits the input from pos to end into lines — each terminator the @@ -182,8 +184,8 @@ func spanLines(input []rune, pos, end int, literals []token.Token) []spanLine { } for j := at; j < len(literals) && literals[j].Pos < i; j++ { lit, stop := literals[j].Pos, literals[j].Pos+literals[j].Len - line.content = line.content || (start > lit && start < stop) - line.open = line.open || (i > lit && i < stop) + line.beginsInString = line.beginsInString || (start > lit && start < stop) + line.endsInString = line.endsInString || (i > lit && i < stop) } lines = append(lines, line) From 8ac6b956d07458a86fe28c57071ba02f528189ad Mon Sep 17 00:00:00 2001 From: Tejas Date: Tue, 24 Nov 2026 19:10:08 +0530 Subject: [PATCH 21/39] docs(lexer): finish the sentence a rename left half-swapped e249d67 renamed the two bits a line carries and replaced the words around the old name in margin's comment without finishing the sentence, which read "A line a literal runs begins inside a string holds its characters". It says what it meant now: a line that begins inside a string holds the string's characters, so it does not set the margin. Co-Authored-By: Claude Fable 5.2 --- lexer/lexer.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/lexer/lexer.go b/lexer/lexer.go index 8f674785..9d36a01f 100644 --- a/lexer/lexer.go +++ b/lexer/lexer.go @@ -127,9 +127,9 @@ func (l *Lexer) Spelling(first, last token.Token, literals []token.Token) string // margin is how far a span's lines move left together: the indentation its // first line stands at, or the least a later line of its own layout has where -// that is less, so nothing a line spells is ever cut. A line a literal runs -// begins inside a string holds its characters, and a blank or comment-only line holds -// nothing of the statement, so neither sets the margin. +// that is less, so nothing a line spells is ever cut. A line that begins +// inside a string holds its characters, and a blank or comment-only line +// holds nothing of the statement, so neither sets the margin. func margin(lines []spanLine, indent int) int { for _, line := range lines[1:] { if indent == 0 { From 997da938fdbb93ab6d7ba87d7667ca25cb6f41ef Mon Sep 17 00:00:00 2001 From: Tejas Date: Tue, 24 Nov 2026 19:10:23 +0530 Subject: [PATCH 22/39] refactor(lexer): take a statement's first line whole Spelling began its span at the first token, past the indentation of that token's line, while every later line arrived with its own. The first line was then padded back with spaces inside the loop that moves the lines left, which read as indentation made up for the occasion. The span begins at the start of first's line now, found as indentation() already finds it from position and column, so every line holds what the file gives it, one rule moves them all, and margin reads the first line's indentation off the line. No program that compiles spells differently: all 5,127 statements of the 124 fixture files are byte for byte what they were. The one difference is on a line the lexer rejects. A statement on a tab-indented line is quoted with its tab, as written, where spaces standing in for the indentation dropped it; such a line is an indentation error and never reaches a plan. That makes the first-spelled-token rule of 7df4812 carry more than it did. The illegal token a tab is lexed as stands at the tab's column, so a span begun there would open before the statement's own line: a tab after two spaces on a file's first line indexes the input at -2. The recovery test's old input, a lone tab at the start of the file, cannot show that, so it uses a tab after spaces on a later line, and fails against both the old start rule and the padding. Co-Authored-By: Claude Fable 5.2 --- lexer/lexer.go | 22 ++++++++++------------ parser/scriptparser_test.go | 11 ++++++----- 2 files changed, 16 insertions(+), 17 deletions(-) diff --git a/lexer/lexer.go b/lexer/lexer.go index 9d36a01f..02656a8e 100644 --- a/lexer/lexer.go +++ b/lexer/lexer.go @@ -92,9 +92,10 @@ func (l *Lexer) createToken(tokenType token.TokenType, literal string, hadSpace return tok } -// Spelling is the source a statement is spelled with: the input from first's -// own start to the end of last, so a comment the statement does not reach is -// never in it. Its lines keep the shape the file gives them, moved left +// Spelling is the source a statement is spelled with: the input from the +// start of first's line to the end of last, so every line holds the +// indentation the file gives it and a comment the statement does not reach +// is never in it. Its lines keep the shape the file gives them, moved left // together by as much as all of them can spare, so a table's hanging header // still stands against its rows. A line a string literal runs into keeps its // characters as they are, since those are what the string holds; literals are @@ -103,18 +104,14 @@ func (l *Lexer) createToken(tokenType token.TokenType, literal string, hadSpace // before last: no other pair names a span of this input, so a caller that // hands one over has a bug that checking here would only move. func (l *Lexer) Spelling(first, last token.Token, literals []token.Token) string { - lines := spanLines(l.input, first.Pos, last.Pos+last.Len, literals) - indent := first.Column - 1 - dedent := margin(lines, indent) + lineStart := first.Pos - (first.Column - 1) + lines := spanLines(l.input, lineStart, last.Pos+last.Len, literals) + dedent := margin(lines) spelled := make([]string, len(lines)) for i, line := range lines { text := line.text - switch { - case line.beginsInString: - case i == 0: - text = strings.Repeat(" ", indent-dedent) + text - default: + if !line.beginsInString { text = text[min(dedent, leading(text)):] } if !line.endsInString { @@ -130,7 +127,8 @@ func (l *Lexer) Spelling(first, last token.Token, literals []token.Token) string // that is less, so nothing a line spells is ever cut. A line that begins // inside a string holds its characters, and a blank or comment-only line // holds nothing of the statement, so neither sets the margin. -func margin(lines []spanLine, indent int) int { +func margin(lines []spanLine) int { + indent := leading(lines[0].text) for _, line := range lines[1:] { if indent == 0 { break diff --git a/parser/scriptparser_test.go b/parser/scriptparser_test.go index ad64811b..9e9464b1 100644 --- a/parser/scriptparser_test.go +++ b/parser/scriptparser_test.go @@ -104,15 +104,16 @@ world" } // A statement the parser recovers is spelled from the first token a source -// spells, not from whatever stood before it. An indent of tabs is reported -// and lexed as a token of its own that spells nothing, and the statement that -// follows it is still quoted as it was written. +// spells, not from whatever stood before it. A tab in an indent is reported +// and lexed as a token of its own that spells nothing and stands at the +// tab's column, so a span begun there would open before the statement's own +// line. Begun at x, it is that line as written, moved left past its spaces. func TestRecoveredStatementSpellsWhatItHas(t *testing.T) { - sp := NewScriptParser(lexer.New("TestRecoveredStatementSpellsWhatItHas", "\tx = 1\nx\n")) + sp := NewScriptParser(lexer.New("TestRecoveredStatementSpellsWhatItHas", "a = 2\n \tx = 1\n")) program := sp.Parse() require.NotEmpty(t, sp.Errors(), "expected the tab indent to be reported") require.Len(t, program.Statements, 2) - require.Equal(t, "x = 1", program.Statements[0].(*ast.LetStatement).Src) + require.Equal(t, "\tx = 1", program.Statements[1].(*ast.LetStatement).Src) } // A run of operator characters the parser splits gives each piece the runes From c4be762ed088a1b6050b3ea2f7e7c300c039900f Mon Sep 17 00:00:00 2001 From: Tejas Date: Wed, 25 Nov 2026 10:46:01 +0530 Subject: [PATCH 23/39] feat(lexer)!: indent a block literal's rows by 4 spaces A block literal's rows could sit at any depth past the line holding its '['. A table's header hangs 2 spaces left of its rows, so it could stand level with its statement, or one column left of it when the rows were one space in. That was the only layout in which a line of a statement began left of the statement, and a function body could hold it where a script could not. Rows now sit exactly 4 spaces past the line holding the '[', as a body or a struct definition does past the line that opens it, which puts a table's header 2 spaces past that line. Rows under a call's continued arguments, the layout the depth was freed for in 8a371a5, still work: since e58a3c8 the depth is measured from the '[' line, not from the statement. BREAKING CHANGE: rows at any other depth are an error, and so is a table header that is not 2 spaces past the line holding its '['. No fixture or docs example used those layouts. Co-Authored-By: Claude Fable 5.2 --- README.md | 8 ++++---- docs/Pluto Array Semantics.md | 9 +++++---- lexer/lexer.go | 10 +++++----- lexer/lexer_test.go | 20 ++++++++++---------- parser/codeparser_test.go | 1 - parser/parser.go | 4 ++-- parser/scriptparser_test.go | 25 +++++++++++++------------ 7 files changed, 39 insertions(+), 38 deletions(-) diff --git a/README.md b/README.md index e5cf90d4..2354bddc 100644 --- a/README.md +++ b/README.md @@ -104,9 +104,9 @@ string literal produces a newline in the string's value -- the `\r` escape denotes a literal carriage return -- so runtime behavior does not depend on how git checks out line endings. -Indentation is significant. A block, such as a template's body or a struct -definition, is indented 4 spaces past the line that opens it, while the rows -of an array literal line up at any depth past it. Tabs are not allowed in +Indentation is significant. A block, such as a template's body, a struct +definition or an array literal's rows, is indented 4 spaces past the line +that opens it. Tabs are not allowed in indentation. A struct's or table's header is written `: name ...`, its `:` 2 spaces left of the values and one space after it, so its names line up with the values. Brackets don't join lines: a line that @@ -298,7 +298,7 @@ where `[` is followed by a newline, contributes row and column axes even when it contains one row. Thus the matrix above is equivalent to `[[1 2] [3 4]]`. Pluto has no line continuation character: an inline array has one row, however long, and a literal whose `[` ends its -line is a block, with its rows lined up at any depth past the line that +line is a block, with its rows 4 spaces past the line that holds the `[`, and `]` on its own line at that line's column, however many lines the statement spans. Array-valued cells stack recursively diff --git a/docs/Pluto Array Semantics.md b/docs/Pluto Array Semantics.md index 2b029c26..02969046 100644 --- a/docs/Pluto Array Semantics.md +++ b/docs/Pluto Array Semantics.md @@ -65,7 +65,7 @@ overflow `I64`. Pluto has no line continuation character, and brackets don't join lines. An inline literal has one row, however long; an editor can wrap it for display. A literal whose `[` ends its line is a block: its -rows line up with each other, at any depth past the line that holds the `[`, +rows are indented 4 spaces past the line that holds the `[`, and its `]` goes on its own line, at that line's column. A line break inside a multi-line string starts no line of its own, so after such a string the line holding the `[` is the one the string began on. A nested block literal follows @@ -81,8 +81,8 @@ matrix = [ A line break between an inline literal's cells or before its `]` is an error, but a cell can itself hold a block literal, a multi-line string or a call continued after a comma. A block literal's `]` on its last row's line or at -another column, and rows that are not indented past the line holding its `[` -or do not line up, are errors too. +another column, and rows that are not 4 spaces past the line holding its `[`, +are errors too. A line breaks only after a comma or `=`, and the next line is indented past the statement's line, so a call's arguments can span lines, as can the names @@ -217,7 +217,8 @@ column name. The header goes on its own line after `[`, with all its column names on that line. Headerless literals start directly with their first data row. -The header's `:` hangs 2 spaces left of the rows, with one space after it, so +The header's `:` hangs 2 spaces left of the rows, so 2 spaces past the line +holding the `[`, with one space after it, so the first header and first value begin in the same column. Spacing within header and data rows is otherwise non-semantic: diff --git a/lexer/lexer.go b/lexer/lexer.go index 02656a8e..9d0390c6 100644 --- a/lexer/lexer.go +++ b/lexer/lexer.go @@ -27,9 +27,9 @@ type Lexer struct { // block is an indented block. Its lines start at level, and the INDENT that // opens it spells out how far that is past the block around it, which the // parser requires to be 4 spaces for a body or a struct definition. A block -// that opens after a line ending in '[' holds that literal's rows, at any -// depth past base, the column of the line holding the '[', and only such a -// block closes, at a ']' line at base. +// that opens after a line ending in '[' holds that literal's rows, 4 spaces +// past base, the column of the line holding the '[', and only such a block +// closes, at a ']' line at base. type block struct { level int holdsRows bool @@ -73,7 +73,7 @@ const ( INDENT_ERR = "indentation error" INDENT_TAB_ERR = "indent using tabs not allowed" BLOCK_CLOSE_ERR = "a block literal's ']' goes on its own line, at the column of the line holding its '['" - BLOCK_ROWS_ERR = "a block literal's rows are indented past the line holding its '['" + BLOCK_ROWS_ERR = "a block literal's rows are indented 4 spaces past the line holding its '[', and a table's header ':' 2" HEADER_COLON_ERR = "a header's ':' has one space after it, so its names line up with the values" ) @@ -358,7 +358,7 @@ func (l *Lexer) placeLine(level, column int, first rune) { at := l.tokenAt(token.INDENT, strings.Repeat(" ", level-around), column) rows := l.last == token.LBRACK var msg string - if rows && level <= l.line { + if rows && level != l.line+4 { msg = BLOCK_ROWS_ERR } l.blocks = append(l.blocks, block{level, rows, l.line}) diff --git a/lexer/lexer_test.go b/lexer/lexer_test.go index c9f875da..f9e5fa8d 100644 --- a/lexer/lexer_test.go +++ b/lexer/lexer_test.go @@ -1488,11 +1488,11 @@ func TestSpellingMovesASpanAsOne(t *testing.T) { src string want string }{ - {"ABodyComesBackToItsOwnLevel", "r = G(x)\n m = [\n 2 3\n ]\n", "m = [\n 2 3\n]"}, - {"AFlushLeftCommentHoldsNothingBack", "r = G(x)\n m = [\n# flush left\n 2 3\n ]\n", "m = [\n# flush left\n 2 3\n]"}, - {"ATabbedCommentHoldsNothingBack", "r = G(x)\n m = [\n\t# tabbed\n 2 3\n ]\n", "m = [\n\t# tabbed\n 2 3\n]"}, - {"ATabOnlyLineHoldsNothingBack", "r = G(x)\n m = [\n\t\n 2 3\n ]\n", "m = [\n\n 2 3\n]"}, - {"AHangingHeaderStandsAgainstItsRows", "r = G(x)\n t = [\n : Name Score\n \"Ada\" 1\n ]\n", " t = [\n: Name Score\n \"Ada\" 1\n ]"}, + {"ABodyComesBackToItsOwnLevel", "r = G(x)\n m = [\n 2 3\n ]\n", "m = [\n 2 3\n]"}, + {"AFlushLeftCommentHoldsNothingBack", "r = G(x)\n m = [\n# flush left\n 2 3\n ]\n", "m = [\n# flush left\n 2 3\n]"}, + {"ATabbedCommentHoldsNothingBack", "r = G(x)\n m = [\n\t# tabbed\n 2 3\n ]\n", "m = [\n\t# tabbed\n 2 3\n]"}, + {"ATabOnlyLineHoldsNothingBack", "r = G(x)\n m = [\n\t\n 2 3\n ]\n", "m = [\n\n 2 3\n]"}, + {"AHangingHeaderStandsAgainstItsRows", "r = G(x)\n t = [\n : Name Score\n \"Ada\" 1\n ]\n", "t = [\n : Name Score\n \"Ada\" 1\n]"}, {"TwoLiteralsOnOneLine", "r = G(x)\n s = \"a\" ⊕ \"b\n c\"\n", "s = \"a\" ⊕ \"b\n c\""}, } for _, tc := range cases { @@ -1515,8 +1515,8 @@ func TestSpelling(t *testing.T) { want string }{ {"OneLineLeavesItsComment", "a = 1 # one\n", "a = 1"}, - {"LinesKeepTheirShape", "m = [\n 2 3\n]\n", "m = [\n 2 3\n]"}, - {"AnInteriorCommentStays", "m = [\n # a row\n 2 3\n]\n", "m = [\n # a row\n 2 3\n]"}, + {"LinesKeepTheirShape", "m = [\n 2 3\n]\n", "m = [\n 2 3\n]"}, + {"AnInteriorCommentStays", "m = [\n # a row\n 2 3\n]\n", "m = [\n # a row\n 2 3\n]"}, {"StringContentKeepsItsSpaces", "w = \"hello \n \nworld\"\n", "w = \"hello \n \nworld\""}, {"ADeeperLineKeepsItsShape", "long =\n a + 1\n", "long =\n a + 1"}, } @@ -1532,9 +1532,9 @@ func TestSpelling(t *testing.T) { // Spelling reads a terminator the same however the file spells it, as the // lexer itself does. func TestSpellingLineEndings(t *testing.T) { - for name, src := range map[string]string{"LF": "m = [\n 2\n]\n", "CRLF": "m = [\r\n 2\r\n]\r\n", "CR": "m = [\r 2\r]\r"} { + for name, src := range map[string]string{"LF": "m = [\n 2\n]\n", "CRLF": "m = [\r\n 2\r\n]\r\n", "CR": "m = [\r 2\r]\r"} { t.Run(name, func(t *testing.T) { - if got, want := spellAll(t, src), "m = [\n 2\n]"; got != want { + if got, want := spellAll(t, src), "m = [\n 2\n]"; got != want { t.Fatalf("Spelling = %q, want %q", got, want) } }) @@ -1545,7 +1545,7 @@ func TestSpellingLineEndings(t *testing.T) { // can quote any span of the input from its tokens alone. A layout token // spells nothing and says so with a zero length. func TestTokenExtents(t *testing.T) { - const src = "a = 5 # one\nm = [\n 2 3\n]\ns = \"x\ny\"\nimp = 5a\nf = -8 >> 1 >>> 2 << 3\ng = a == b != c <= d >= e\nh = .5\nt = [\n : Name Score\n \"Ada\" 1\n]\n" + const src = "a = 5 # one\nm = [\n 2 3\n]\ns = \"x\ny\"\nimp = 5a\nf = -8 >> 1 >>> 2 << 3\ng = a == b != c <= d >= e\nh = .5\nt = [\n : Name Score\n \"Ada\" 1\n]\n" l := New("TestTokenExtents", src) runes := []rune(src) for { diff --git a/parser/codeparser_test.go b/parser/codeparser_test.go index b5e7a898..95c95e86 100644 --- a/parser/codeparser_test.go +++ b/parser/codeparser_test.go @@ -274,7 +274,6 @@ func TestLayoutInBody(t *testing.T) { {"call continued after a comma", " y = f(x,\n 1)\n"}, {"comma after a multi-line string", " y = f(\"a\nb\",\n [1 2])\n"}, {"block literal after a multi-line string", " y = f(\"a\nb\", [\n 2 3\n ])\n"}, - {"table header one column left of its statement", " y = [\n : a b\n 1 2\n ]\n"}, } { t.Run(tt.name, func(t *testing.T) { input := "y = F(x)\n" + tt.body + " y = y\nz = G(x)\n z = x\n" diff --git a/parser/parser.go b/parser/parser.go index 0dd7d815..f632359d 100644 --- a/parser/parser.go +++ b/parser/parser.go @@ -1262,8 +1262,8 @@ func (p *StmtParser) parseInlineLiteral(arr *ast.ArrayLiteral) bool { } // parseBlockLiteral reads a literal whose '[' ends its line: an optional -// header and the rows, as a block at any depth past the statement or row -// holding its '[', then the ']' on its own line. It leaves curToken at the ']'. +// header and the rows, as a block 4 spaces past the line holding its '[', +// then the ']' on its own line. It leaves curToken at the ']'. func (p *StmtParser) parseBlockLiteral(arr *ast.ArrayLiteral) bool { if p.peekTokenIs(token.RBRACK) { p.nextToken() diff --git a/parser/scriptparser_test.go b/parser/scriptparser_test.go index 9e9464b1..18e3e44f 100644 --- a/parser/scriptparser_test.go +++ b/parser/scriptparser_test.go @@ -63,8 +63,8 @@ n = -a imp = 5a f = -8 >> 1 # arithmetic right shift m = [ - 1 2 - 3 4 + 1 2 + 3 4 ] long = a + 1 @@ -79,7 +79,7 @@ world" "n = -a", "imp = 5a", "f = -8 >> 1", - "m = [\n 1 2\n 3 4\n]", + "m = [\n 1 2\n 3 4\n]", "long =\n a + 1", "w = \"hello \n \n\t\nworld\"", `"out: -b -n"`, @@ -147,7 +147,7 @@ func TestSpellingReparses(t *testing.T) { "b = a + 2 * 3\n", "imp = 5a\n", "f = -8 >> 1 # arithmetic right shift\n", - "m = [\n 1 2\n 3 4\n]\n", + "m = [\n 1 2\n 3 4\n]\n", "long =\n a + 1\n", "w = \"hello \n \n\t\nworld\"\n", "s = \"a\nb\"\n\"out: -s\"\n", @@ -195,8 +195,8 @@ line two" # flush left x + 1 v = [ - : Name Score - "Ada" 1 + : Name Score + "Ada" 1 ] r = t + 1 ` @@ -215,7 +215,7 @@ line two" spelled = append(spelled, inner.(*ast.LetStatement).Src) } } - require.Equal(t, []string{"t = x * 2", "s = \"line one\nline two\"", "u =\n# flush left\n x + 1", " v = [\n: Name Score\n \"Ada\" 1\n ]", "r = t + 1"}, spelled) + require.Equal(t, []string{"t = x * 2", "s = \"line one\nline two\"", "u =\n# flush left\n x + 1", "v = [\n : Name Score\n \"Ada\" 1\n]", "r = t + 1"}, spelled) } func TestInvalidAssignment(t *testing.T) { @@ -1802,14 +1802,15 @@ func TestLayoutKeepsStatements(t *testing.T) { }{ {"nested block literals", "x = [\n [\n 1 2\n ]\n]", nil}, {"block literal", "m = [\n 1 2\n 3 4\n]", nil}, - {"rows at any depth past the statement", "m = [\n 1 2\n 3 4\n]", nil}, + {"rows 2 spaces past the statement", "m = [\n 1 2\n 3 4\n]", []string{name + "2:3:" + blockRowsErr}}, + {"rows 8 spaces past the statement", "m = [\n 1 2\n 3 4\n]", []string{name + "2:9:" + blockRowsErr}}, {"rows under a '[' on a continued line", "x = f(1,\n [\n 2 3\n ])", nil}, - {"rows of a '[' in the middle of its line", "x = f(1, [\n 2 3\n], a,\n b)", nil}, - {"']' aligned under a '[' in the middle of its line", "x = f(1, [\n 2 3\n ],\n a,\n b)", []string{name + "3:12:" + blockCloseErr}}, + {"rows of a '[' in the middle of its line", "x = f(1, [\n 2 3\n], a,\n b)", nil}, + {"']' aligned under a '[' in the middle of its line", "x = f(1, [\n 2 3\n ],\n a,\n b)", []string{name + "3:12:" + blockCloseErr}}, {"empty literal's ']' on a continued line", "x = f(1,\n [\n ]0)", nil}, {"empty literal's ']' indented", "x = [\n ]0", []string{name + "2:9:" + blockCloseErr}}, - {"table header at its statement's column", "t = [\n: a b\n 1 2\n]", nil}, - {"row left of the first row", "m = [\n 1 2\n 3 4\n]", []string{name + "3:5:" + lexer.INDENT_ERR + ". At char: 3"}}, + {"table header at its statement's column", "t = [\n: a b\n 1 2\n]", []string{name + "2:1:" + blockRowsErr}}, + {"row left of the first row", "m = [\n 1 2\n 3 4\n]", []string{name + "3:3:" + lexer.INDENT_ERR + ". At char: 3"}}, {"unclosed block literal", "x = [\n 1 2", []string{name + "3:1:" + blockCloseErr}}, {"unclosed block table", "t = [\n : Name(\"\") Score(0)", []string{name + "3:1:" + blockCloseErr}}, {"inline literal across lines", "x = [1 2\n 3 4]", []string{name + "1:9:" + inlineArrayErr}}, From a0b7d9303dd1e68bba713ed7a3dfbd708e8f5f8d Mon Sep 17 00:00:00 2001 From: Tejas Date: Wed, 25 Nov 2026 10:46:01 +0530 Subject: [PATCH 24/39] refactor(lexer): take a statement's indent off its later lines Spelling took a statement's first line whole and moved every line left by the least indentation they could all spare, which margin found by reading each line past blanks, comments and strings. The one layout that needed it was a table header standing left of its statement, which is no longer legal. Every line of a statement now has the indentation the statement stands at. Spelling starts at the first token and takes that much off each later line, and a blank or comment line gives up what it has. margin is gone, and so is the arithmetic that found the first line's start. Starting at the first token also keeps a recovered statement to itself. After a tab indent it is "x = 1", where 997da93 gave the tab too, and after a NUL that ends a comment early it no longer carries the comment's text; a test pins each. No plan is built from either file. Every statement in the fixtures is spelled as before. Co-Authored-By: Claude Fable 5.2 --- docs/Pluto IR Plan.md | 8 +++--- lexer/lexer.go | 51 ++++++++++--------------------------- lexer/lexer_test.go | 7 +++-- parser/scriptparser_test.go | 16 +++++++++--- 4 files changed, 34 insertions(+), 48 deletions(-) diff --git a/docs/Pluto IR Plan.md b/docs/Pluto IR Plan.md index 1a709402..c007794a 100644 --- a/docs/Pluto IR Plan.md +++ b/docs/Pluto IR Plan.md @@ -742,10 +742,10 @@ rather than an operand: the label stands alone and the statement's own lines sit one level in, so a block literal reads as it is laid out (decided 2026-11-23). What it renders is the file's own text, from the statement's first token to its last: a comment the statement does not reach is never in -it, while one between two of its own tokens is. The lines move left together, -by the least indentation they can all spare, so a table's header still hangs -where it stood against its rows; a line holding nothing of the statement — -blank, or a comment at any indentation — neither sets that margin nor loses +it, while one between two of its own tokens is. Each later line loses the +indentation the statement stands at, which the layout rules give every line +of its own, so the lines keep the shape the file gives them; a line holding +nothing of the statement — blank, or a comment at any indentation — loses no more than it has, and a line a string literal runs through keeps the characters the string holds. So the parens the ast adds to spell out its own nesting are absent diff --git a/lexer/lexer.go b/lexer/lexer.go index 9d0390c6..7b27b3fc 100644 --- a/lexer/lexer.go +++ b/lexer/lexer.go @@ -92,27 +92,26 @@ func (l *Lexer) createToken(tokenType token.TokenType, literal string, hadSpace return tok } -// Spelling is the source a statement is spelled with: the input from the -// start of first's line to the end of last, so every line holds the -// indentation the file gives it and a comment the statement does not reach -// is never in it. Its lines keep the shape the file gives them, moved left -// together by as much as all of them can spare, so a table's hanging header -// still stands against its rows. A line a string literal runs into keeps its -// characters as they are, since those are what the string holds; literals are -// the string tokens the statement spans, in source order. first and last are -// tokens this lexer produced, each spelling source of its own, first at or -// before last: no other pair names a span of this input, so a caller that -// hands one over has a bug that checking here would only move. +// Spelling is the source a statement is spelled with: the input from first +// to the end of last, so a comment the statement does not reach is never in +// it. Its lines keep the shape the file gives them: each later one loses the +// indentation the statement stands at, which the layout rules give every +// line of its own, and a blank or comment line loses what it has of that. A +// line a string literal runs into keeps its characters as they are, since +// those are what the string holds; literals are the string tokens the +// statement spans, in source order. first and last are tokens this lexer +// produced, each spelling source of its own, first at or before last: no +// other pair names a span of this input, so a caller that hands one over has +// a bug that checking here would only move. func (l *Lexer) Spelling(first, last token.Token, literals []token.Token) string { - lineStart := first.Pos - (first.Column - 1) - lines := spanLines(l.input, lineStart, last.Pos+last.Len, literals) - dedent := margin(lines) + indent := first.Column - 1 + lines := spanLines(l.input, first.Pos, last.Pos+last.Len, literals) spelled := make([]string, len(lines)) for i, line := range lines { text := line.text if !line.beginsInString { - text = text[min(dedent, leading(text)):] + text = text[min(indent, leading(text)):] } if !line.endsInString { text = strings.TrimRight(text, " \t") @@ -122,28 +121,6 @@ func (l *Lexer) Spelling(first, last token.Token, literals []token.Token) string return strings.Join(spelled, "\n") } -// margin is how far a span's lines move left together: the indentation its -// first line stands at, or the least a later line of its own layout has where -// that is less, so nothing a line spells is ever cut. A line that begins -// inside a string holds its characters, and a blank or comment-only line -// holds nothing of the statement, so neither sets the margin. -func margin(lines []spanLine) int { - indent := leading(lines[0].text) - for _, line := range lines[1:] { - if indent == 0 { - break - } - // A blank or comment line may be indented with tabs, which no line - // of the statement's own may be, so what it holds is read past both. - held := strings.TrimLeft(line.text, " \t") - if line.beginsInString || held == "" || strings.HasPrefix(held, "#") { - continue - } - indent = min(indent, leading(line.text)) - } - return indent -} - // leading counts the spaces a line opens with. func leading(text string) int { return len(text) - len(strings.TrimLeft(text, " ")) diff --git a/lexer/lexer_test.go b/lexer/lexer_test.go index f9e5fa8d..e9c14b1d 100644 --- a/lexer/lexer_test.go +++ b/lexer/lexer_test.go @@ -1478,9 +1478,9 @@ func spellFrom(t *testing.T, src string, from int) string { return l.Spelling(first, last, literals) } -// A span an indented statement makes moves left as one, by as much as all of -// its lines can spare. A line holding nothing of the statement — blank or a -// comment, however it is indented — neither sets that margin nor loses more +// A span an indented statement makes moves left as one: each later line +// loses the indentation the statement stands at. A line holding nothing of +// the statement — blank or a comment, however it is indented — loses no more // than it has. func TestSpellingMovesASpanAsOne(t *testing.T) { cases := []struct { @@ -1492,7 +1492,6 @@ func TestSpellingMovesASpanAsOne(t *testing.T) { {"AFlushLeftCommentHoldsNothingBack", "r = G(x)\n m = [\n# flush left\n 2 3\n ]\n", "m = [\n# flush left\n 2 3\n]"}, {"ATabbedCommentHoldsNothingBack", "r = G(x)\n m = [\n\t# tabbed\n 2 3\n ]\n", "m = [\n\t# tabbed\n 2 3\n]"}, {"ATabOnlyLineHoldsNothingBack", "r = G(x)\n m = [\n\t\n 2 3\n ]\n", "m = [\n\n 2 3\n]"}, - {"AHangingHeaderStandsAgainstItsRows", "r = G(x)\n t = [\n : Name Score\n \"Ada\" 1\n ]\n", "t = [\n : Name Score\n \"Ada\" 1\n]"}, {"TwoLiteralsOnOneLine", "r = G(x)\n s = \"a\" ⊕ \"b\n c\"\n", "s = \"a\" ⊕ \"b\n c\""}, } for _, tc := range cases { diff --git a/parser/scriptparser_test.go b/parser/scriptparser_test.go index 18e3e44f..a035b96c 100644 --- a/parser/scriptparser_test.go +++ b/parser/scriptparser_test.go @@ -106,14 +106,24 @@ world" // A statement the parser recovers is spelled from the first token a source // spells, not from whatever stood before it. A tab in an indent is reported // and lexed as a token of its own that spells nothing and stands at the -// tab's column, so a span begun there would open before the statement's own -// line. Begun at x, it is that line as written, moved left past its spaces. +// tab's column, so a span begun there would hold the tab. Begun at x, it is +// the statement alone. func TestRecoveredStatementSpellsWhatItHas(t *testing.T) { sp := NewScriptParser(lexer.New("TestRecoveredStatementSpellsWhatItHas", "a = 2\n \tx = 1\n")) program := sp.Parse() require.NotEmpty(t, sp.Errors(), "expected the tab indent to be reported") require.Len(t, program.Statements, 2) - require.Equal(t, "\tx = 1", program.Statements[1].(*ast.LetStatement).Src) + require.Equal(t, "x = 1", program.Statements[1].(*ast.LetStatement).Src) +} + +// Nothing before a statement's first token on its line is spelled with it. +// Only an error leaves text there: a NUL ends a comment early, and the +// statement the parser recovers starts at the NUL. +func TestRecoveredStatementExcludesEarlierComment(t *testing.T) { + sp := NewScriptParser(lexer.New("TestRecoveredStatementExcludesEarlierComment", "# ignored\t\x00 x = 1\n")) + program := sp.Parse() + require.NotEmpty(t, sp.Errors(), "expected the NUL to be reported") + require.Equal(t, "\x00 x = 1", requireOnlyLetStmt(t, program).Src) } // A run of operator characters the parser splits gives each piece the runes From 0455967d9da95a7675eb358669d34fe90032ebb8 Mon Sep 17 00:00:00 2001 From: Tejas Date: Wed, 25 Nov 2026 13:21:24 +0530 Subject: [PATCH 25/39] fix(lexer,parser): judge a block literal's row depth in the parser c4be762 fixed a block literal's rows at 4 spaces by checking the depth in the lexer, on the line after any '[' that ends its line. The lexer cannot tell whether that '[' opens a block literal, so an index broken across lines, `x = a[` with its next line 2 spaces in, drew "a block literal's rows are indented 4 spaces" ahead of the real error. It also put a depth in the lexer, where 49c56fc had left none: the lexer measures and the parser judges. That holds for rows again. A rows block's INDENT spells out how far the rows are past the line holding the '[', the line they hang from, as a body's spells out how far it is past its block, and the lexer reports nothing about it. Where the parser opens a block literal's rows it checks that INDENT as it checks a body's, with the rows' message, so the 4 is written in the parser alone. Rows at or left of that line spell no indentation and are reported the same way. lexer.BLOCK_ROWS_ERR goes with the lexer's check, as INDENT_WIDTH_ERR did in 49c56fc; the message is the parser's blockRowsErr, and nothing outside the parser named the constant. The lexer still places a header line 2 columns right of its ':', the width of the ':' and its one space: that is what makes a header and its rows one block of tokens, which is layout rather than a rule about depth. An index broken across lines whose ']' stands off its line's column still draws the ']' message after the real one, as it does on master. Co-Authored-By: Claude Fable 5.2 --- lexer/lexer.go | 20 +++++++++----------- lexer/lexer_test.go | 8 ++++---- parser/parser.go | 15 ++++++++------- parser/scriptparser_test.go | 6 ++++-- 4 files changed, 25 insertions(+), 24 deletions(-) diff --git a/lexer/lexer.go b/lexer/lexer.go index 7b27b3fc..36a51e94 100644 --- a/lexer/lexer.go +++ b/lexer/lexer.go @@ -25,11 +25,10 @@ type Lexer struct { } // block is an indented block. Its lines start at level, and the INDENT that -// opens it spells out how far that is past the block around it, which the -// parser requires to be 4 spaces for a body or a struct definition. A block -// that opens after a line ending in '[' holds that literal's rows, 4 spaces -// past base, the column of the line holding the '[', and only such a block -// closes, at a ']' line at base. +// opens it spells out how far that is past what the block hangs from, for the +// parser to judge: the block around it, or for a literal's rows base, the +// column of the line holding the '['. A block of rows opens after a line +// ending in '[', and only such a block closes, at a ']' line at base. type block struct { level int holdsRows bool @@ -73,7 +72,6 @@ const ( INDENT_ERR = "indentation error" INDENT_TAB_ERR = "indent using tabs not allowed" BLOCK_CLOSE_ERR = "a block literal's ']' goes on its own line, at the column of the line holding its '['" - BLOCK_ROWS_ERR = "a block literal's rows are indented 4 spaces past the line holding its '[', and a table's header ':' 2" HEADER_COLON_ERR = "a header's ':' has one space after it, so its names line up with the values" ) @@ -332,14 +330,14 @@ func (l *Lexer) startLine(column int, first rune, tab int) { // returns to it; any other line is reported. func (l *Lexer) placeLine(level, column int, first rune) { if around := l.level(len(l.blocks)); level > around { - at := l.tokenAt(token.INDENT, strings.Repeat(" ", level-around), column) rows := l.last == token.LBRACK - var msg string - if rows && level != l.line+4 { - msg = BLOCK_ROWS_ERR + from := around + if rows { + from = l.line } + at := l.tokenAt(token.INDENT, strings.Repeat(" ", max(0, level-from)), column) l.blocks = append(l.blocks, block{level, rows, l.line}) - l.pending.push(lexed{at, msg}) + l.pending.push(lexed{tok: at}) return } n := len(l.blocks) diff --git a/lexer/lexer_test.go b/lexer/lexer_test.go index e9c14b1d..fe8d145c 100644 --- a/lexer/lexer_test.go +++ b/lexer/lexer_test.go @@ -1017,7 +1017,7 @@ func TestLineLayout(t *testing.T) { {token.COMMA, ",", "", 1, 8}, {token.LBRACK, "[", "", 2, 5}, {token.NEWLINE, "\n", "", 2, 6}, - {token.INDENT, " ", "", 3, 9}, + {token.INDENT, " ", "", 3, 9}, {token.INT, "2", "", 3, 9}, {token.NEWLINE, "\n", "", 3, 10}, {token.DEINDENT, "]", "", 4, 5}, @@ -1028,7 +1028,7 @@ func TestLineLayout(t *testing.T) { }) }) - t.Run("a block literal's rows and ']' are reported away from the line holding its '['", func(t *testing.T) { + t.Run("rows at the column of the line holding their '[' spell no indentation, and a ']' elsewhere is reported", func(t *testing.T) { checkInput(t, "x = f(1,\n [\n 2\n])", []Test{ {token.IDENT, "x", "", 1, 1}, {token.ASSIGN, "=", "", 1, 3}, @@ -1038,7 +1038,7 @@ func TestLineLayout(t *testing.T) { {token.COMMA, ",", "", 1, 8}, {token.LBRACK, "[", "", 2, 5}, {token.NEWLINE, "\n", "", 2, 6}, - {token.INDENT, " ", "3:5:" + BLOCK_ROWS_ERR, 3, 5}, + {token.INDENT, "", "", 3, 5}, {token.INT, "2", "", 3, 5}, {token.NEWLINE, "\n", "", 3, 6}, {token.DEINDENT, "]", "", 4, 1}, @@ -1080,7 +1080,7 @@ func TestLineLayout(t *testing.T) { {token.COMMA, ",", "", 1, 8}, {token.LBRACK, "[", "", 2, 5}, {token.NEWLINE, "\n", "", 2, 6}, - {token.INDENT, " ", "", 3, 9}, + {token.INDENT, " ", "", 3, 9}, {token.INT, "2", "", 3, 9}, {token.NEWLINE, "\n", "", 3, 10}, {token.DEINDENT, "]", "", 4, 5}, diff --git a/parser/parser.go b/parser/parser.go index f632359d..52a13d66 100644 --- a/parser/parser.go +++ b/parser/parser.go @@ -753,7 +753,7 @@ func (p *StmtParser) parseStructLiteralStatement(assignTok token.Token, idents [ if !p.peekTokenIs(token.INDENT) { return stmt } - p.checkBlockIndent(p.peekToken) + p.checkBlockIndent(p.peekToken, blockIndentErr) p.nextToken() // consume INDENT p.nextToken() // move to first token in the struct body if !p.parseStructBody(stmt.Value) { @@ -1203,7 +1203,7 @@ const ( blockIndentErr = "indent a body or a struct definition by 4 spaces, and a struct's header ':' by 2, with one space after it" strayIndentErr = "unexpected indentation: the line before it opens no block" inlineArrayErr = "an inline array stays on one line; to span lines, end the line with '[' and indent its rows" - blockRowsErr = lexer.BLOCK_ROWS_ERR + blockRowsErr = "a block literal's rows are indented 4 spaces past the line holding its '[', and a table's header ':' 2" blockCloseErr = lexer.BLOCK_CLOSE_ERR lineBreakErr = "a value is expected before the line ends; a line continues only after a comma or '=', onto an indented line" parenBreakErr = "expected ')' before the line ends; inside parentheses, a line continues only after a comma, onto an indented line" @@ -1273,6 +1273,7 @@ func (p *StmtParser) parseBlockLiteral(arr *ast.ArrayLiteral) bool { p.errors = append(p.errors, &token.CompileError{Token: p.peekToken, Msg: blockRowsErr}) return false } + p.checkBlockIndent(p.peekToken, blockRowsErr) p.nextToken() // the line break after '[' p.nextToken() // the rows' INDENT @@ -1327,11 +1328,11 @@ func (p *StmtParser) skipLine() { } } -// checkBlockIndent reports a block that its INDENT says is not indented 4 -// spaces past the line that opens it. -func (p *StmtParser) checkBlockIndent(indent token.Token) { +// checkBlockIndent reports, with msg, a block that its INDENT says is not +// indented 4 spaces past the line it hangs from. +func (p *StmtParser) checkBlockIndent(indent token.Token, msg string) { if indent.Literal != blockIndent { - p.errors = append(p.errors, &token.CompileError{Token: indent, Msg: blockIndentErr}) + p.errors = append(p.errors, &token.CompileError{Token: indent, Msg: msg}) } } @@ -1726,7 +1727,7 @@ func (p *StmtParser) lineUp(continued *int) { // assumes current token is token.NEWLINE func (p *StmtParser) parseBlockStatement() *ast.BlockStatement { if p.peekTokenIs(token.INDENT) { - p.checkBlockIndent(p.peekToken) + p.checkBlockIndent(p.peekToken, blockIndentErr) } else { p.peekError(token.INDENT) } diff --git a/parser/scriptparser_test.go b/parser/scriptparser_test.go index a035b96c..7009ae76 100644 --- a/parser/scriptparser_test.go +++ b/parser/scriptparser_test.go @@ -1836,6 +1836,7 @@ func TestLayoutKeepsStatements(t *testing.T) { {"table closed on its header's line", "t = [\n : a b]", []string{name + "2:8:" + blockCloseErr}}, {"block literal's ']' at its rows' column", "m = [\n 1 2\n ]", []string{name + "3:5:" + blockCloseErr}}, {"rows at the column of the line holding '['", "x = f(1,\n [\n 2 3\n ])", []string{name + "3:5:" + blockRowsErr}}, + {"rows left of the line holding '['", "x = f(1,\n [\n 2 3\n ])", []string{name + "3:5:" + blockRowsErr}}, {"nested call's continued arguments", "x = f(a,\n g(b,\n c),\n d)", nil}, {"call continued after '='", "x =\n f(a,\n b)", nil}, {"calls joined by an operator", "x = f(a,\n b) + g(c,\n d)", nil}, @@ -2081,9 +2082,10 @@ func statementStrings(stmts []ast.Statement) []string { return strs } -// An index bracket keeps its expression on its line. +// An index bracket keeps its expression on its line. The line after it is no +// literal's rows, so how far it is indented is not judged. func TestIndexStaysOnOneLine(t *testing.T) { - sp := NewScriptParser(lexer.New("TestIndexStaysOnOneLine", "value = data[\n i]")) + sp := NewScriptParser(lexer.New("TestIndexStaysOnOneLine", "value = data[\n i]")) sp.Parse() require.Equal(t, []string{"TestIndexStaysOnOneLine:1:14:" + lineBreakErr}, sp.Errors()) } From f2cc31ac9420f4c217ff0eb5573d4082094c6493 Mon Sep 17 00:00:00 2001 From: Tejas Date: Wed, 25 Nov 2026 17:40:03 +0530 Subject: [PATCH 26/39] refactor(parser): give a split operator's pieces their plain lengths splitOperator clamped the length of each piece it cuts an operator run into, min(matched, tok.Len) for the first and max(tok.Len-matched, 0) for the rest. Neither clamp can act. The run's length is the number of runes in its literal, the matched operator is a prefix of that literal, and the second piece is only built when something is left, so the first piece is matched runes long and the rest is what remains. The clamps came with 20afc33 as a guard against a state no path produces. All 2,115 operator tokens in the fixtures have a length equal to their literal's, and TestSplitOperatorKeepsItsRunes fails if either length is wrong. Co-Authored-By: Claude Fable 5.2 --- parser/parser.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/parser/parser.go b/parser/parser.go index 52a13d66..fc56925f 100644 --- a/parser/parser.go +++ b/parser/parser.go @@ -294,7 +294,7 @@ func (p *StmtParser) splitOperator(tok token.Token, opType OpType) []token.Token Line: tok.Line, Column: tok.Column, Pos: tok.Pos, - Len: min(matched, tok.Len), + Len: matched, // Preserve source spacing so attached-prefix boundary checks still // work after an operator run is split into parseable pieces. HadSpace: tok.HadSpace, @@ -310,7 +310,7 @@ func (p *StmtParser) splitOperator(tok token.Token, opType OpType) []token.Token Line: tok.Line, Column: tok.Column + matched, Pos: tok.Pos + matched, - Len: max(tok.Len-matched, 0), + Len: tok.Len - matched, }) } From 5feaade9e47c41d3e66517b5b3ef6a6d1f1b1de2 Mon Sep 17 00:00:00 2001 From: Tejas Date: Wed, 25 Nov 2026 20:11:18 +0530 Subject: [PATCH 27/39] test(parser): pin the lengths a split operator's first split gives MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit f2cc31a said TestSplitOperatorKeepsItsRunes fails if either piece's length is wrong. It does not. The test reads the pieces of "√-" from the AST, and both are one rune, so the remainder given the matched length, or the first piece given the run's length less the matched one, passed the whole parser suite. No parse can show the difference: only a prefix run is split, and every prefix operator is one rune, so the pieces a parse ends with are all one rune long. TestSplitOperatorPlacesItsRemainder calls splitOperator on "√--", whose pieces are one rune and two, and checks that each spells its own runes. It also checks each piece's column, which no parser test pinned: a remainder left at the run's column passed too. Co-Authored-By: Claude Fable 5.2 --- parser/scriptparser_test.go | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/parser/scriptparser_test.go b/parser/scriptparser_test.go index 7009ae76..a72c6bbb 100644 --- a/parser/scriptparser_test.go +++ b/parser/scriptparser_test.go @@ -149,6 +149,24 @@ func TestSplitOperatorKeepsItsRunes(t *testing.T) { require.Equal(t, root.Tok().Pos+root.Tok().Len, inner.Tok().Pos, "the pieces must follow one another") } +// The first split of a longer run leaves a remainder of several runes, which +// the next split measures its own pieces from. Every prefix operator is one +// rune, so the pieces a parse ends with are all one rune long and cannot show +// a length taken from the wrong piece; the first split of "√--" does. On a +// file's first line a piece's column is one past its position. +func TestSplitOperatorPlacesItsRemainder(t *testing.T) { + const script = "√--x\n" + p := New(lexer.New("TestSplitOperatorPlacesItsRemainder", script)) + pieces := p.splitOperator(p.curToken, PrefixOp) + require.Len(t, pieces, 2) + + runes := []rune(script) + for _, tok := range pieces { + require.Equal(t, tok.Literal, string(runes[tok.Pos:tok.Pos+tok.Len])) + require.Equal(t, tok.Pos+1, tok.Column, "operator %q", tok.Literal) + } +} + // A statement's spelling holds everything the statement does, so parsing it // on its own gives the same statement back. That catches a span that dropped // or added a character where no golden names it. From f980ba14d16bde04e8e439ce3059faa625fce519 Mon Sep 17 00:00:00 2001 From: Tejas Date: Thu, 26 Nov 2026 09:35:31 +0530 Subject: [PATCH 28/39] refactor(parser): remove the infix operator split that never ran parseExpressionTail called normalizePeekInfixOperator to split a run such as "*-" at its longest infix operator. It never split one. The loop first compares the run's precedence, and only a run that is an operator itself has one, so a run that could be split stopped the loop before the call and a run that reached the call matched whole. `a*-b` has always been an operator "*-" that nothing defines, which is the rule the language keeps: a run of operator characters between two values is one operator. The call goes, with normalizePeekInfixOperator, the OpType switch that chose between the prefix and infix tables, and findLongestOp's infix arm. splitOperator splits a run that begins a value at its first prefix operator, the one thing it ever did, and says so. TestOperatorRunBetweenValuesIsOneOperator pins the reading of `a*-b`. No statement parses differently: the fixtures' 5,127 statements are what they were. Co-Authored-By: Claude Fable 5.2 --- parser/parser.go | 53 ++++++++----------------------------- parser/scriptparser_test.go | 11 +++++++- 2 files changed, 21 insertions(+), 43 deletions(-) diff --git a/parser/parser.go b/parser/parser.go index fc56925f..3c3cc88b 100644 --- a/parser/parser.go +++ b/parser/parser.go @@ -245,40 +245,26 @@ func (p *StmtParser) handleImplicitMult() { // ============ Operator Splitting ============ -type OpType int - -const ( - PrefixOp OpType = iota - InfixOp -) - -// findLongestOp finds the longest matching operator in the parse function map -func (p *StmtParser) findLongestOp(lit string, opType OpType) string { +// findLongestPrefixOp finds the longest prefix operator lit starts with. +func (p *StmtParser) findLongestPrefixOp(lit string) string { best := "" - switch opType { - case PrefixOp: - for op := range p.prefixParseFns { - if strings.HasPrefix(lit, op) && len(op) > len(best) { - best = op - } - } - case InfixOp: - for op := range p.infixParseFns { - if strings.HasPrefix(lit, op) && len(op) > len(best) { - best = op - } + for op := range p.prefixParseFns { + if strings.HasPrefix(lit, op) && len(op) > len(best) { + best = op } } return best } -// splitOperator splits "√-" -> ["√", "-"] -func (p *StmtParser) splitOperator(tok token.Token, opType OpType) []token.Token { +// splitOperator splits a run that begins a value at its first prefix +// operator: "√-" -> ["√", "-"]. A run between two values is never split: it +// is one operator, defined or not, so "a*-b" names an operator "*-". +func (p *StmtParser) splitOperator(tok token.Token) []token.Token { if tok.Type != token.OPERATOR { return []token.Token{tok} } - match := p.findLongestOp(tok.Literal, opType) + match := p.findLongestPrefixOp(tok.Literal) if match == "" || match == tok.Literal { return []token.Token{tok} // No split needed } @@ -319,7 +305,7 @@ func (p *StmtParser) splitOperator(tok token.Token, opType OpType) []token.Token // normalizeCurrentPrefixOperator splits current token for prefix parsing func (p *StmtParser) normalizeCurrentPrefixOperator() { - tokens := p.splitOperator(p.curToken, PrefixOp) + tokens := p.splitOperator(p.curToken) if len(tokens) <= 1 { return } @@ -340,18 +326,6 @@ func (p *StmtParser) normalizeCurrentPrefixOperator() { p.savedTokens = append(queue, p.savedTokens...) } -// normalizePeekInfixOperator splits peek token for infix parsing -func (p *StmtParser) normalizePeekInfixOperator() { - tokens := p.splitOperator(p.peekToken, InfixOp) - if len(tokens) <= 1 { - return - } - - // Replace peek with matched part, queue the rest - p.peekToken = tokens[0] - p.savedTokens = append(tokens[1:], p.savedTokens...) -} - func (p *StmtParser) curTokenIs(t token.TokenType) bool { return p.curToken.Type == t } @@ -1022,11 +996,6 @@ func (p *StmtParser) parseExpressionTail(precedence float64, splitPrefix prefixS break } - // Normalize operator first to get its true form - if p.peekToken.Type == token.OPERATOR { - p.normalizePeekInfixOperator() - } - infix := p.infixParseFns[p.peekToken.TokenTypeWithOp()] if infix == nil { return left diff --git a/parser/scriptparser_test.go b/parser/scriptparser_test.go index a72c6bbb..7b024b16 100644 --- a/parser/scriptparser_test.go +++ b/parser/scriptparser_test.go @@ -157,7 +157,7 @@ func TestSplitOperatorKeepsItsRunes(t *testing.T) { func TestSplitOperatorPlacesItsRemainder(t *testing.T) { const script = "√--x\n" p := New(lexer.New("TestSplitOperatorPlacesItsRemainder", script)) - pieces := p.splitOperator(p.curToken, PrefixOp) + pieces := p.splitOperator(p.curToken) require.Len(t, pieces, 2) runes := []rune(script) @@ -167,6 +167,15 @@ func TestSplitOperatorPlacesItsRemainder(t *testing.T) { } } +// A run of operator characters between two values is one operator, so "*-" +// is an operator nothing defines, not a product with a negation. +func TestOperatorRunBetweenValuesIsOneOperator(t *testing.T) { + const name = "TestOperatorRunBetweenValuesIsOneOperator" + sp := NewScriptParser(lexer.New(name, "x = a*-b\n")) + sp.Parse() + require.Equal(t, []string{name + ":1:6:no prefix parse function for *- found"}, sp.Errors()) +} + // A statement's spelling holds everything the statement does, so parsing it // on its own gives the same statement back. That catches a span that dropped // or added a character where no golden names it. From 6bf6693b14e6261f25a06db1b425347b0ce22a8f Mon Sep 17 00:00:00 2001 From: Tejas Date: Thu, 26 Nov 2026 09:35:32 +0530 Subject: [PATCH 29/39] feat(parser)!: report an operator run that names no operator MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A run of operator characters that names no operator was never reported as one. It ended the value before it, and whatever came next complained: `x = a*-b` said "no prefix parse function for *- found", `x = f(a*-b)` said "expected next token to be ), got OPERATOR", and `a @= 2` blamed the `a`. When the run was made of prefix operators nothing complained at all: `[a-√b]` was two cells, `a` and `-√b`, and `x = a > 1-√b` was the condition `a > 1` with the value `-√b`. A run is one operator. Attached to the value before it, it stands between two values, so it has to be an operator that takes two, and one that nothing defines is reported at the run as `operator -√ is not defined`. After a space, a run made of prefix operators begins the next value where one may begin: a row's next cell, or a statement's value after its condition. Where no value may begin, as in `x = 1 -√b` and `f(a -√b)`, it is the same error. At a value's start a run is split only when it is made of prefix operators alone, so `-*b` is an undefined `-*` and not a negation of `*b`. Operators that are defined keep their reading. `*` before a value still has "no prefix parse function for * found", and a prefix-only operator begins a value wherever it stands, so `[a√b]` is still two cells, as tests/array/array_neg.spt pins. The docs state the rule beside the one for cells, with the three spellings of `a`, `-` and `√b`. BREAKING CHANGE: a run of prefix operators attached to the value before it no longer begins a new value. `[a-√b]` printed `[16 -2]` for a = 16 and b = 4 and is now `operator -√ is not defined`; `[a--b]` and `x = a > 1-√b` fail the same way. Put a space before the run where a new value is meant (`[a -√b]`, `x = a > 1 -√b`), or spaces on both sides where one operator is (`[a - √b]`). No fixture, README or docs example needed the change. Co-Authored-By: Claude Fable 5.2 --- docs/Pluto Conditional Value Semantics.md | 10 ++++ parser/parser.go | 56 +++++++++++++++++++++-- parser/scriptparser_test.go | 46 +++++++++++++++---- 3 files changed, 97 insertions(+), 15 deletions(-) diff --git a/docs/Pluto Conditional Value Semantics.md b/docs/Pluto Conditional Value Semantics.md index 13514560..504aa669 100644 --- a/docs/Pluto Conditional Value Semantics.md +++ b/docs/Pluto Conditional Value Semantics.md @@ -354,6 +354,16 @@ Spacing separates cells, and operators glue their operands into one cell: [a > 3 && b < 5 || 10] # one cell ``` +A run of operator characters is one operator. Attached to the value before it, +it stands between two values, so it has to be an operator that takes two. After +a space, a run made of prefix operators begins the next cell: + +```pluto +[a - √b] # one cell: a minus √b +[a -√b] # two cells: a and -√b +[a-√b] # error: operator -√ is not defined +``` + A direct array comparison follows the same rule element-wise: `arr > k` is a **mask** — each cell keeps its left value where the comparison holds, else 0, *in place* (length- and position-preserving). It is the scalar "yield the left diff --git a/parser/parser.go b/parser/parser.go index 3c3cc88b..0361f09c 100644 --- a/parser/parser.go +++ b/parser/parser.go @@ -256,16 +256,30 @@ func (p *StmtParser) findLongestPrefixOp(lit string) string { return best } +// isPrefixRun reports whether lit is made of prefix operators alone, so that +// a value may begin with it. +func (p *StmtParser) isPrefixRun(lit string) bool { + for lit != "" { + op := p.findLongestPrefixOp(lit) + if op == "" { + return false + } + lit = lit[len(op):] + } + return true +} + // splitOperator splits a run that begins a value at its first prefix -// operator: "√-" -> ["√", "-"]. A run between two values is never split: it -// is one operator, defined or not, so "a*-b" names an operator "*-". +// operator: "√-" -> ["√", "-"]. Only a run made of prefix operators alone is +// split. Any other is one operator, defined or not, as a run between two +// values always is, so "a*-b" names an operator "*-". func (p *StmtParser) splitOperator(tok token.Token) []token.Token { - if tok.Type != token.OPERATOR { + if tok.Type != token.OPERATOR || !p.isPrefixRun(tok.Literal) { return []token.Token{tok} } match := p.findLongestPrefixOp(tok.Literal) - if match == "" || match == tok.Literal { + if match == tok.Literal { return []token.Token{tok} // No split needed } @@ -377,6 +391,11 @@ func (p *StmtParser) curError(t token.TokenType) { } func (p *StmtParser) noPrefixParseFnError(t token.Token) { + if p.isUndefinedOperator(t) { + p.undefinedOperatorError(t) + return + } + msg := fmt.Sprintf("no prefix parse function for %s found", t.TokenTypeWithOp()) ce := &token.CompileError{ Token: p.curToken, @@ -966,7 +985,34 @@ func (p *StmtParser) parseExpression(precedence float64, splitPrefix prefixSplit return nil } - return p.parseExpressionTail(precedence, splitPrefix, leftExp) + value := p.parseExpressionTail(precedence, splitPrefix, leftExp) + if value == nil || precedence > LOWEST || !p.isUndefinedOperator(p.peekToken) { + return value + } + + // A whole value, parsed at LOWEST, ends at a run that is no operator. Made + // of prefix operators and with a space before it, the run begins the next + // value where one may begin. Any other stands between two values as one + // operator, which nothing defines; it is read past, as a failed part is. + if p.peekToken.HadSpace && p.isPrefixRun(p.peekToken.Literal) && p.shouldSplitAttachedPrefix(splitPrefix, value) { + return value + } + p.nextToken() + p.undefinedOperatorError(p.curToken) + return nil +} + +// isUndefinedOperator reports whether tok is a run of operator characters +// that names no operator, neither before a value nor between two. +func (p *StmtParser) isUndefinedOperator(tok token.Token) bool { + return tok.Type == token.OPERATOR && p.prefixParseFns[tok.Literal] == nil && p.infixParseFns[tok.Literal] == nil +} + +func (p *StmtParser) undefinedOperatorError(tok token.Token) { + p.errors = append(p.errors, &token.CompileError{ + Token: tok, + Msg: fmt.Sprintf("operator %s is not defined", tok.Literal), + }) } // parseExpressionTail continues parsing an expression using precedence climbing. diff --git a/parser/scriptparser_test.go b/parser/scriptparser_test.go index 7b024b16..5f9a1315 100644 --- a/parser/scriptparser_test.go +++ b/parser/scriptparser_test.go @@ -167,13 +167,39 @@ func TestSplitOperatorPlacesItsRemainder(t *testing.T) { } } -// A run of operator characters between two values is one operator, so "*-" -// is an operator nothing defines, not a product with a negation. -func TestOperatorRunBetweenValuesIsOneOperator(t *testing.T) { - const name = "TestOperatorRunBetweenValuesIsOneOperator" - sp := NewScriptParser(lexer.New(name, "x = a*-b\n")) - sp.Parse() - require.Equal(t, []string{name + ":1:6:no prefix parse function for *- found"}, sp.Errors()) +// A run of operator characters that names no operator is reported as that, +// once and whole, at the run. Only a run made of prefix operators begins a +// value, and after a value only with a space before it, where a value may +// begin: "a-√b" is no difference with a root, and "-*" is no negation. An +// operator that is defined keeps its own reading: "*" before a value has its +// own error, and "√" begins a value wherever it stands. +func TestUndefinedOperatorRun(t *testing.T) { + const name = "TestUndefinedOperatorRun:" + for _, tt := range []struct{ input, err string }{ + {"x = a-√b", "1:6:operator -√ is not defined"}, + {"x = 1 -√b", "1:7:operator -√ is not defined"}, + {"x = f(a -√b)", "1:9:operator -√ is not defined"}, + {"x = [a*-b]", "1:7:operator *- is not defined"}, + {"x = -*b", "1:5:operator -* is not defined"}, + {"x, y = a, b @ c", "1:13:operator @ is not defined"}, + {"x = *b", "1:5:no prefix parse function for * found"}, + } { + sp := NewScriptParser(lexer.New("TestUndefinedOperatorRun", tt.input+"\nafter = 3")) + program := sp.Parse() + require.Equal(t, []string{name + tt.err}, sp.Errors(), tt.input) + require.Equal(t, []string{"after = 3"}, statementStrings(program.Statements), tt.input) + } + + for _, tt := range []struct{ input, parsed string }{ + {"x = a > 1 -√c", "x = (a > 1) (-(√c))"}, + {"x = [1 -√4]", "x = [1 (-(√4))]"}, + {"x = [a√b]", "x = [a (√b)]"}, + } { + sp := NewScriptParser(lexer.New("TestUndefinedOperatorRun", tt.input)) + program := sp.Parse() + require.Empty(t, sp.Errors(), tt.input) + require.Equal(t, []string{tt.parsed}, statementStrings(program.Statements), tt.input) + } } // A statement's spelling holds everything the statement does, so parsing it @@ -286,16 +312,16 @@ func TestUnparsedAssignmentTarget(t *testing.T) { "TestUnparsedAssignmentTarget:1:1:expected next token to be =, got . instead", }}, {"operator run", "a @= 2", []string{ - "TestUnparsedAssignmentTarget:1:1:expected next token to be =, got OPERATOR instead", + "TestUnparsedAssignmentTarget:1:3:operator @ is not defined", }}, {"closing paren", "a ) = 2", []string{ "TestUnparsedAssignmentTarget:1:1:expected next token to be =, got ) instead", }}, {"only target", "@ = 2", []string{ - "TestUnparsedAssignmentTarget:1:1:no prefix parse function for @ found", + "TestUnparsedAssignmentTarget:1:1:operator @ is not defined", }}, {"second target", "a, @ = 2, 3", []string{ - "TestUnparsedAssignmentTarget:1:4:no prefix parse function for @ found", + "TestUnparsedAssignmentTarget:1:4:operator @ is not defined", }}, } From 40f6b12ecbcd5c2315ef4009c46d9ffacba36743 Mon Sep 17 00:00:00 2001 From: Tejas Date: Thu, 26 Nov 2026 09:35:32 +0530 Subject: [PATCH 30/39] fix(parser): end a failed cell where its brackets close An array row is the one place the parser reads on after a failure, so that a later cell can still report its own error. A cell that failed inside its brackets stopped there, and the row read what was left of it as cells: `x = [f(a@b, c)]` reported the undefined `@` and then the `,` and the `)`, three errors for one mistake. A broken index did the opposite. Its `]` was taken for the row's, so the row ended early and `x = [v[a@b] c@d]` never reported the second `@`. The parser now counts the parentheses and square brackets open where a token stands, kept by nextToken. After each cell the row reads on until the brackets that cell opened are closed, stopping short of the row's own `]` and at the end of the line. That is one rule in parseRow; a call, a group and an index need no recovery of their own, and none of them can tell its own closer from one an inner failure stopped on. Each cell counts from where it starts, so a stray `)` earlier in the row changes nothing for the cells after it. `[f(a@b, c)]` and `[(a@b) c]` now give one error each, `[f(a@b, c) d@e]` two, and `[v[a@b] c@d]` both of its own. Outside a row nothing changes: a statement that fails skips its line, as before. One row reports less. Where a `)` is missing altogether the row cannot tell where the call ends and reads to its own end, so `[f(a b c@d]` gives the missing `)` and not the `@` behind it, which shows once the first is fixed. No row reports an error that is not there. The counts are exact for brackets that nest. A stack that knew each bracket's kind would also read on in `[[f(a b] c@d]`; it is not built. Co-Authored-By: Claude Fable 5.2 --- parser/parser.go | 45 ++++++++++++++++++++++++++++++++++++- parser/scriptparser_test.go | 28 +++++++++++++++++++++++ 2 files changed, 72 insertions(+), 1 deletion(-) diff --git a/parser/parser.go b/parser/parser.go index 0361f09c..85397969 100644 --- a/parser/parser.go +++ b/parser/parser.go @@ -83,6 +83,31 @@ type ( postfixParseFn func(ast.Expression) ast.Expression ) +// brackets counts the parentheses and square brackets open where a token +// stands. An opener counts once the parser is past it and a closer as soon as +// it is current, so a value that closes what it opens ends at the count it +// started at. +type brackets struct { + parens, squares int +} + +// move takes the count from the token passed to the one now current. +func (b *brackets) move(passed, current token.TokenType) { + switch passed { + case token.LPAREN: + b.parens++ + case token.LBRACK: + b.squares++ + } + + switch current { + case token.RPAREN: + b.parens-- + case token.RBRACK: + b.squares-- + } +} + // Token Management System for Pluto Parser // // Token flow: [Lexer] -> peekToken -> curToken @@ -103,6 +128,7 @@ type StmtParser struct { stmtEnd token.Token // the last token of it a source spells stmtLiterals []token.Token // the string literals it spans savedTokens []token.Token // FIFO queue of synthetic tokens from operator splits or inserting a * in something like 9x + open brackets // the brackets open where curToken stands prefixParseFns map[string]prefixParseFn infixParseFns map[string]infixParseFn @@ -180,7 +206,9 @@ func New(l *lexer.Lexer) *StmtParser { func (p *StmtParser) nextToken() { // always advance current token + passed := p.curToken.Type p.curToken = p.peekToken + p.open.move(passed, p.curToken.Type) p.noteSpelled(p.curToken) // get new peek token from queue or lexer @@ -1581,13 +1609,15 @@ func (p *StmtParser) parseColumnType(header token.Token) (ast.Expression, bool) // parseRow parses a row's cells up to a ']' or the end of its line, where it // stops, and adds the row to arr unless it is empty. A cell that fails leaves -// the row failed, and the row reads on. +// the row failed, and the row reads on past the brackets the cell left open. func (p *StmtParser) parseRow(arr *ast.ArrayLiteral) bool { row := []ast.Expression{} ok := true for !p.curTokenIs(token.RBRACK) && !p.atLineEnd() { + start := p.open expr := p.parseExpression(LOWEST, prefixSplitAlways) + p.leaveBrackets(start) ok = ok && expr != nil if expr != nil { row = append(row, expr) @@ -1604,6 +1634,19 @@ func (p *StmtParser) parseRow(arr *ast.ArrayLiteral) bool { return ok } +// leaveBrackets reads on to the token that closes the last bracket opened +// since start, where a cell that failed inside its brackets ends. It stops +// short of a ']' that closes none of them, which is the row's own, and at the +// end of the line. +func (p *StmtParser) leaveBrackets(start brackets) { + for p.open.parens > start.parens || p.open.squares > start.squares { + if p.atLineEnd() || p.peekTokenIs(token.RBRACK) && p.open.squares == start.squares { + return + } + p.nextToken() + } +} + // parseRangeLiteral is called when we encounter a ':' in an infix position. // The `left` argument is the expression that was just parsed before the ':'. func (p *StmtParser) parseRangeLiteral(left ast.Expression) ast.Expression { diff --git a/parser/scriptparser_test.go b/parser/scriptparser_test.go index 5f9a1315..1477bb9c 100644 --- a/parser/scriptparser_test.go +++ b/parser/scriptparser_test.go @@ -2038,6 +2038,34 @@ func TestFailedPartFailsWhatHoldsIt(t *testing.T) { } } +// A cell that fails inside its brackets takes them with it. The row reads on +// from the cell after, so what is left of a failed call, group or index is not +// read as cells, and a later cell still reports its own error. Each cell +// counts its own brackets, so a stray ')' before it changes nothing. A ']' +// that closes none of the cell's brackets stays the row's own. +func TestFailedCellTakesItsBrackets(t *testing.T) { + const name = "TestFailedCellTakesItsBrackets:" + const undefined = "operator @ is not defined" + for _, tt := range []struct { + input string + errs []string + }{ + {"x = [f(a@b, c) ) (d@e) g@h]", []string{"1:9:" + undefined, "1:16:no prefix parse function for ) found", "1:20:" + undefined, "1:25:" + undefined}}, + {"x = [v[a@b] c@d]", []string{"1:9:" + undefined, "1:14:" + undefined}}, + {"x = g([f(a b], c@d)", []string{"1:10:expected next token to be ), got IDENT instead", "1:17:" + undefined}}, + } { + sp := NewScriptParser(lexer.New("TestFailedCellTakesItsBrackets", tt.input+"\nafter = 3")) + program := sp.Parse() + + var errs []string + for _, err := range tt.errs { + errs = append(errs, name+err) + } + require.Equal(t, errs, sp.Errors(), tt.input) + require.Equal(t, []string{"after = 3"}, statementStrings(program.Statements), tt.input) + } +} + // The end of the input ends its last line as a line break does, so a line // cut short there gets the error it gets before a newline. func TestLastLineEndsAtEndOfInput(t *testing.T) { From f13f5233da20a3483c6954833428167417d761e5 Mon Sep 17 00:00:00 2001 From: Tejas Date: Thu, 26 Nov 2026 09:35:32 +0530 Subject: [PATCH 31/39] refactor(parser): drop spell's test for a statement that failed spell returned early for a nil statement. Its switch already does nothing for one, since nil is neither of the two statements a plan quotes, so the test only saved computing a spelling nobody reads. Spelling is still handed tokens it can quote: a statement starts at a token its source spells whether or not it parses, so the span is one of this input. The two cases stay two, because Src is a field of each statement and not of ast.Statement. Co-Authored-By: Claude Fable 5.2 --- parser/parser.go | 3 --- 1 file changed, 3 deletions(-) diff --git a/parser/parser.go b/parser/parser.go index 85397969..d470cae6 100644 --- a/parser/parser.go +++ b/parser/parser.go @@ -476,9 +476,6 @@ func (p *StmtParser) noteSpelled(tok token.Token) { // so what a reader sees is what they wrote. func (p *StmtParser) spell(stmt ast.Statement) { p.spelling = false - if stmt == nil { - return - } src := p.l.Spelling(p.stmtStart, p.stmtEnd, p.stmtLiterals) switch s := stmt.(type) { From ba9f7bf87f0b54278051386600a104c72e65aff8 Mon Sep 17 00:00:00 2001 From: Codex Date: Thu, 26 Nov 2026 09:36:50 +0530 Subject: [PATCH 32/39] fix(parser): quote source only for completed statements Attach the source directly when returning a let or a print, and stop recording on every exit. A code file whose function has no indented body can return nil without recording a source token. Preserve its parse diagnostic without sending an empty span to the lexer. --- parser/codeparser_test.go | 6 ++++++ parser/parser.go | 26 ++++++-------------------- 2 files changed, 12 insertions(+), 20 deletions(-) diff --git a/parser/codeparser_test.go b/parser/codeparser_test.go index 95c95e86..ebc2d717 100644 --- a/parser/codeparser_test.go +++ b/parser/codeparser_test.go @@ -262,6 +262,12 @@ func TestUnparsedAssignmentTargetInBody(t *testing.T) { }, p.Errors()) } +func TestMissingBodyIndentReportsError(t *testing.T) { + p := NewCodeParser(lexer.New("missing-indent.pt", "r = F()\nx")) + require.Nil(t, p.Parse()) + require.Contains(t, p.Errors(), "missing-indent.pt:1:8:expected next token to be INDENT, got IDENT instead") +} + // A literal inside a function body keeps the body's block structure, however // its lines are indented. func TestLayoutInBody(t *testing.T) { diff --git a/parser/parser.go b/parser/parser.go index d470cae6..cdadc8f3 100644 --- a/parser/parser.go +++ b/parser/parser.go @@ -470,36 +470,24 @@ func (p *StmtParser) noteSpelled(tok token.Token) { } } -// spell gives stmt the source its file spells it with, from the token the -// statement started at to the last one it spells, and closes the recording -// noteSpelled does. A plan quotes that rather than the ast's own rendering, -// so what a reader sees is what they wrote. -func (p *StmtParser) spell(stmt ast.Statement) { - p.spelling = false - - src := p.l.Spelling(p.stmtStart, p.stmtEnd, p.stmtLiterals) - switch s := stmt.(type) { - case *ast.LetStatement: - s.Src = src - case *ast.PrintStatement: - s.Src = src - } +func (p *StmtParser) sourceSpelling() string { + return p.l.Spelling(p.stmtStart, p.stmtEnd, p.stmtLiterals) } // parseStatement parses one statement and gives it the source its file // spells it with. The recording runs for exactly as long as this does, so a // caller that parses a declaration of its own keeps none of its tokens. -func (p *StmtParser) parseStatement() (stmt ast.Statement) { +func (p *StmtParser) parseStatement() ast.Statement { if p.skipIndented() { return nil } firstToken := p.curToken p.spelling = true + defer func() { p.spelling = false }() p.stmtStart = token.Token{} p.stmtEnd = token.Token{} p.stmtLiterals = p.stmtLiterals[:0] p.noteSpelled(firstToken) - defer func() { p.spell(stmt) }() p.blankIdents = nil // reset for new statement expList := p.parseExpList(prefixSplitNone, 0) // An expression that failed to parse is nil and has already reported its @@ -514,6 +502,7 @@ func (p *StmtParser) parseStatement() (stmt ast.Statement) { p.errorOnBlanks() return &ast.PrintStatement{ Token: firstToken, + Src: p.sourceSpelling(), Expression: &ast.CallExpression{ Token: firstToken, Function: &ast.Identifier{Token: firstToken, Value: ""}, @@ -536,11 +525,8 @@ func (p *StmtParser) parseStatement() (stmt ast.Statement) { } p.checkNoDuplicates(identList) - // A nil *ast.LetStatement is not a nil ast.Statement, so the let is named - // and tested rather than returned straight through. It is not named stmt: - // this function returns one, and nothing should have to ask which the - // deferred spelling reads. if let := p.parseLetStatement(identList); let != nil { + let.Src = p.sourceSpelling() return let } return nil From b7331558595c3915c4a470b78afbd7a27b57d7bc Mon Sep 17 00:00:00 2001 From: Codex Date: Thu, 26 Nov 2026 09:36:52 +0530 Subject: [PATCH 33/39] perf(parser): split a prefix operator run in linear time MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Decompose a validated run together and queue its tokens in source order. This avoids walking all remaining suffixes at every recursive prefix parse while preserving each operator’s position and leading-space flag. --- parser/parser.go | 90 +++++++++++++------------------------ parser/scriptparser_test.go | 11 +++-- 2 files changed, 38 insertions(+), 63 deletions(-) diff --git a/parser/parser.go b/parser/parser.go index cdadc8f3..002f2c99 100644 --- a/parser/parser.go +++ b/parser/parser.go @@ -297,75 +297,45 @@ func (p *StmtParser) isPrefixRun(lit string) bool { return true } -// splitOperator splits a run that begins a value at its first prefix -// operator: "√-" -> ["√", "-"]. Only a run made of prefix operators alone is -// split. Any other is one operator, defined or not, as a run between two -// values always is, so "a*-b" names an operator "*-". -func (p *StmtParser) splitOperator(tok token.Token) []token.Token { - if tok.Type != token.OPERATOR || !p.isPrefixRun(tok.Literal) { - return []token.Token{tok} - } - - match := p.findLongestPrefixOp(tok.Literal) - if match == tok.Literal { - return []token.Token{tok} // No split needed - } - - // Split into matched part and remainder. Each piece keeps the runes of - // the run that spell it, so a token still says where its own source is. +// splitOperator takes a matched prefix off an operator run. Both pieces keep +// their source extents, and only the first inherits the run's leading space. +func splitOperator(tok token.Token, match string) (token.Token, token.Token) { matched := utf8.RuneCountInString(match) - result := []token.Token{ - { - Type: token.OPERATOR, - Literal: match, - FileName: tok.FileName, - Line: tok.Line, - Column: tok.Column, - Pos: tok.Pos, - Len: matched, - // Preserve source spacing so attached-prefix boundary checks still - // work after an operator run is split into parseable pieces. - HadSpace: tok.HadSpace, - }, - } + first := tok + first.Literal = match + first.Len = matched - remainder := tok.Literal[len(match):] - if remainder != "" { - result = append(result, token.Token{ - Type: token.OPERATOR, - Literal: remainder, - FileName: tok.FileName, - Line: tok.Line, - Column: tok.Column + matched, - Pos: tok.Pos + matched, - Len: tok.Len - matched, - }) - } - - return result + tok.Literal = tok.Literal[len(match):] + tok.Pos += matched + tok.Column += matched + tok.Len -= matched + tok.HadSpace = false + return first, tok } -// normalizeCurrentPrefixOperator splits current token for prefix parsing +// A run that begins a value must consist entirely of prefix operators. +// Queue the pieces together so each suffix can be consumed directly. func (p *StmtParser) normalizeCurrentPrefixOperator() { - tokens := p.splitOperator(p.curToken) - if len(tokens) <= 1 { + rest := p.curToken + if p.prefixParseFns[rest.Literal] != nil || !p.isPrefixRun(rest.Literal) { return } - // Update current to matched part, queue the rest - p.curToken = tokens[0] - - // Set next token to the immediate remainder part, and queue the original peek - // plus any further remainder (avoiding duplicating tokens[1]). - originalPeek := p.peekToken - p.peekToken = tokens[1] - - queue := []token.Token{} - if len(tokens) > 2 { - queue = append(queue, tokens[2:]...) + var pieces []token.Token + for { + match := p.findLongestPrefixOp(rest.Literal) + if match == rest.Literal { + break + } + first, remainder := splitOperator(rest, match) + pieces = append(pieces, first) + rest = remainder } - queue = append(queue, originalPeek) - p.savedTokens = append(queue, p.savedTokens...) + + pieces = append(pieces, rest, p.peekToken) + p.curToken = pieces[0] + p.peekToken = pieces[1] + p.savedTokens = append(pieces[2:], p.savedTokens...) } func (p *StmtParser) curTokenIs(t token.TokenType) bool { diff --git a/parser/scriptparser_test.go b/parser/scriptparser_test.go index 1477bb9c..66b083f9 100644 --- a/parser/scriptparser_test.go +++ b/parser/scriptparser_test.go @@ -157,14 +157,19 @@ func TestSplitOperatorKeepsItsRunes(t *testing.T) { func TestSplitOperatorPlacesItsRemainder(t *testing.T) { const script = "√--x\n" p := New(lexer.New("TestSplitOperatorPlacesItsRemainder", script)) - pieces := p.splitOperator(p.curToken) - require.Len(t, pieces, 2) + first, remainder := splitOperator(p.curToken, "√") runes := []rune(script) - for _, tok := range pieces { + for _, tok := range []token.Token{first, remainder} { require.Equal(t, tok.Literal, string(runes[tok.Pos:tok.Pos+tok.Len])) require.Equal(t, tok.Pos+1, tok.Column, "operator %q", tok.Literal) } + + p.normalizeCurrentPrefixOperator() + for _, want := range []string{"√", "-", "-", "x"} { + require.Equal(t, want, p.curToken.Literal) + p.nextToken() + } } // A run of operator characters that names no operator is reported as that, From 7597f31c9102df5999eba52931b0893daddbe502 Mon Sep 17 00:00:00 2001 From: Codex Date: Thu, 26 Nov 2026 09:36:53 +0530 Subject: [PATCH 34/39] fix(parser): diagnose an undefined run after a positional value MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A comma starts another positional value. Only the initial expression can introduce a statement condition. Report a space-prefixed run such as -√ at the run itself when it follows a positional value. --- parser/parser.go | 3 ++- parser/scriptparser_test.go | 1 + 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/parser/parser.go b/parser/parser.go index 002f2c99..3fe9ba68 100644 --- a/parser/parser.go +++ b/parser/parser.go @@ -927,7 +927,8 @@ func (p *StmtParser) parseExpList(splitPrefix prefixSplitMode, continued int) [] p.nextToken() p.lineUp(&continued) p.nextToken() - expList = append(expList, p.parseExpression(LOWEST, splitPrefix)) + // A comma starts a positional value. Only the first expression can be a gate. + expList = append(expList, p.parseExpression(LOWEST, prefixSplitNone)) } return expList } diff --git a/parser/scriptparser_test.go b/parser/scriptparser_test.go index 66b083f9..31082643 100644 --- a/parser/scriptparser_test.go +++ b/parser/scriptparser_test.go @@ -187,6 +187,7 @@ func TestUndefinedOperatorRun(t *testing.T) { {"x = [a*-b]", "1:7:operator *- is not defined"}, {"x = -*b", "1:5:operator -* is not defined"}, {"x, y = a, b @ c", "1:13:operator @ is not defined"}, + {"x, y = a, b -√c", "1:13:operator -√ is not defined"}, {"x = *b", "1:5:no prefix parse function for * found"}, } { sp := NewScriptParser(lexer.New("TestUndefinedOperatorRun", tt.input+"\nafter = 3")) From e82680a5e2e0f2cebbea8f10132a9c45749d7b1c Mon Sep 17 00:00:00 2001 From: Codex Date: Thu, 26 Nov 2026 09:38:27 +0530 Subject: [PATCH 35/39] docs(parser): distinguish a named prefix operator from a run Show why a root can start an attached array cell while a combined prefix run requires a leading space. The examples describe the spacing used by existing rows and the migration for attached runs. --- docs/Pluto Conditional Value Semantics.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/docs/Pluto Conditional Value Semantics.md b/docs/Pluto Conditional Value Semantics.md index 504aa669..38415894 100644 --- a/docs/Pluto Conditional Value Semantics.md +++ b/docs/Pluto Conditional Value Semantics.md @@ -354,14 +354,15 @@ Spacing separates cells, and operators glue their operands into one cell: [a > 3 && b < 5 || 10] # one cell ``` -A run of operator characters is one operator. Attached to the value before it, -it stands between two values, so it has to be an operator that takes two. After -a space, a run made of prefix operators begins the next cell: +A named prefix-only operator such as `√` can start a cell even when it touches +the previous cell. A run such as `-√` has no operator of its own. It can start +the next cell when a space separates it from the previous value. ```pluto [a - √b] # one cell: a minus √b [a -√b] # two cells: a and -√b [a-√b] # error: operator -√ is not defined +[a√b] # two cells: a and √b ``` A direct array comparison follows the same rule element-wise: `arr > k` is a From 0976ecb3ed36a31db842bc7d535521bbd41b042a Mon Sep 17 00:00:00 2001 From: Tejas Date: Thu, 26 Nov 2026 10:46:40 +0530 Subject: [PATCH 36/39] test(parser): pin that a list item after a comma takes no condition MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 7597f31 stopped splitting at a spaced prefix after a comma, and its one test is the error for an undefined run, `x, y = a, b -√c`. Nothing pinned what the change does to a defined operator: with the old split put back for defined operators alone, every test passed. TestCommaStartsPositionalValue parses `x, y, z = 1, n -1, b > 2 -5` and checks that the statement has no condition and the values `1`, `n - 1` and `(b > 2) - 5`. The two items are the two shapes master rejected with "a statement condition is a single expression", one after an identifier and one after a comparison. That mutant now fails it. Co-Authored-By: Claude Fable 5.2 --- parser/scriptparser_test.go | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/parser/scriptparser_test.go b/parser/scriptparser_test.go index 31082643..41dc48d4 100644 --- a/parser/scriptparser_test.go +++ b/parser/scriptparser_test.go @@ -907,6 +907,19 @@ func TestCommaConditionRejected(t *testing.T) { require.Contains(t, sp.Errors()[0], "a statement condition is a single expression; combine conditions with &&") } +// After a comma nothing begins a condition's value, so a spaced minus there +// is a subtraction, after an identifier and after a comparison alike, and +// the statement has no condition. +func TestCommaStartsPositionalValue(t *testing.T) { + sp := NewScriptParser(lexer.New("TestCommaStartsPositionalValue", "x, y, z = 1, n -1, b > 2 -5")) + program := sp.Parse() + require.Empty(t, sp.Errors()) + + stmt := requireOnlyLetStmt(t, program) + require.Empty(t, stmt.Condition) + require.Equal(t, "x, y, z = 1, (n - 1), ((b > 2) - 5)", stmt.String()) +} + func TestConditionListBesideArithmetic(t *testing.T) { // Arithmetic inside a condition takes parentheses; after the condition // list, it starts the value. From 52e7a1f2bbc838990361d87842a7fcd9e517e3bf Mon Sep 17 00:00:00 2001 From: Tejas Date: Thu, 26 Nov 2026 10:46:40 +0530 Subject: [PATCH 37/39] test(parser): pin that a single prefix operator is not queued again normalizeCurrentPrefixOperator returns early for an operator that is one prefix operator already. Without that return the parse is the same, so no test noticed, but the function then rebuilds the queue of waiting tokens for every operator of a run it has already split. 4,096 `-` before a value allocate 689 MB against 1.94 MB, which is the quadratic cost b733155 removed, back in memory instead of time. TestSinglePrefixOperatorIsNotRequeued asks for no allocation when the current token is a lone `-`. It measures one with the early return removed. A count needs no timing threshold, and it holds under the race detector. Co-Authored-By: Claude Fable 5.2 --- parser/scriptparser_test.go | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/parser/scriptparser_test.go b/parser/scriptparser_test.go index 41dc48d4..d041477f 100644 --- a/parser/scriptparser_test.go +++ b/parser/scriptparser_test.go @@ -172,6 +172,14 @@ func TestSplitOperatorPlacesItsRemainder(t *testing.T) { } } +// An operator that is one prefix operator already is left as it is, with no +// queue built for it. Queuing it again copies every token still waiting, once +// for each operator of a run, which makes a long run quadratic. +func TestSinglePrefixOperatorIsNotRequeued(t *testing.T) { + p := New(lexer.New("TestSinglePrefixOperatorIsNotRequeued", "-x\n")) + require.Zero(t, testing.AllocsPerRun(100, p.normalizeCurrentPrefixOperator)) +} + // A run of operator characters that names no operator is reported as that, // once and whole, at the run. Only a run made of prefix operators begins a // value, and after a value only with a space before it, where a value may From 126f7257820b3219c7f1773279220a567552d6fa Mon Sep 17 00:00:00 2001 From: Tejas Date: Thu, 26 Nov 2026 10:46:41 +0530 Subject: [PATCH 38/39] fix(parser): end a row at its own ']' when a cell fails on it A cell that failed at its row's own ']' left the row reading on. parseRow stepped past the token every cell ends on, which here was that ']', and took what followed the literal for cells: `x = f([1 +], 9)` reported the missing operand and then the `,` and the `)`. master does the same. The bracket counts already say when this has happened. A closer counts as soon as it is current, so once a cell leaves fewer square brackets open than it started with, the row's own ']' has been reached, and the row stops there. An index the cell opened and closed leaves the count where it was, so `[v[1 +] c@d]` still reads its second cell. `x = f([1 +], 9)` goes from three errors to one, and `x = [f([1 +], 9) c@d]` from four to its two real ones. 40f6b12 said no row reports an error that is not there. That was wrong, and this is the case that shows it. What was measured since: of 276 inputs holding one fault each, in rows, calls, groups and indexes, 34 reported more than one error before this change, all of this kind, and each reports exactly one after it. Co-Authored-By: Claude Fable 5.2 --- parser/parser.go | 4 ++++ parser/scriptparser_test.go | 5 ++++- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/parser/parser.go b/parser/parser.go index 3fe9ba68..ebec2b4e 100644 --- a/parser/parser.go +++ b/parser/parser.go @@ -1564,6 +1564,7 @@ func (p *StmtParser) parseColumnType(header token.Token) (ast.Expression, bool) // parseRow parses a row's cells up to a ']' or the end of its line, where it // stops, and adds the row to arr unless it is empty. A cell that fails leaves // the row failed, and the row reads on past the brackets the cell left open. +// A cell that fails at the row's own ']' has ended the row. func (p *StmtParser) parseRow(arr *ast.ArrayLiteral) bool { row := []ast.Expression{} ok := true @@ -1576,6 +1577,9 @@ func (p *StmtParser) parseRow(arr *ast.ArrayLiteral) bool { if expr != nil { row = append(row, expr) } + if p.open.squares < start.squares { + break + } if !p.atLineEnd() { p.nextToken() } diff --git a/parser/scriptparser_test.go b/parser/scriptparser_test.go index d041477f..a85f10a2 100644 --- a/parser/scriptparser_test.go +++ b/parser/scriptparser_test.go @@ -2069,7 +2069,9 @@ func TestFailedPartFailsWhatHoldsIt(t *testing.T) { // from the cell after, so what is left of a failed call, group or index is not // read as cells, and a later cell still reports its own error. Each cell // counts its own brackets, so a stray ')' before it changes nothing. A ']' -// that closes none of the cell's brackets stays the row's own. +// that closes none of the cell's brackets stays the row's own, and a cell +// that fails at it has ended the row: what follows the literal is not read as +// its cells. func TestFailedCellTakesItsBrackets(t *testing.T) { const name = "TestFailedCellTakesItsBrackets:" const undefined = "operator @ is not defined" @@ -2080,6 +2082,7 @@ func TestFailedCellTakesItsBrackets(t *testing.T) { {"x = [f(a@b, c) ) (d@e) g@h]", []string{"1:9:" + undefined, "1:16:no prefix parse function for ) found", "1:20:" + undefined, "1:25:" + undefined}}, {"x = [v[a@b] c@d]", []string{"1:9:" + undefined, "1:14:" + undefined}}, {"x = g([f(a b], c@d)", []string{"1:10:expected next token to be ), got IDENT instead", "1:17:" + undefined}}, + {"x = [f([1 +], 9) c@d]", []string{"1:12:no prefix parse function for ] found", "1:19:" + undefined}}, } { sp := NewScriptParser(lexer.New("TestFailedCellTakesItsBrackets", tt.input+"\nafter = 3")) program := sp.Parse() From 6d774def9651183c14122feac4a01f82e2550816 Mon Sep 17 00:00:00 2001 From: Tejas Date: Thu, 26 Nov 2026 12:06:10 +0530 Subject: [PATCH 39/39] feat(lexer,parser): end a statement's source at its line break A statement's source ran from its first token to its last. A comment after the last token was outside that span and was cut, while a comment any earlier line of the statement ended with lay between two of its tokens and was kept: v = [ # opens "Ada" 1 # top scorer ] "# closes" was cut here A one-line statement has only a last line, so its comment was always cut. The source now runs to the line break that ends the statement, so every line keeps what it ends with: `t = x * 2 # doubled` is spelled whole. A blank left after the last token or the comment is still trimmed, and the lines around the statement are still not part of it. Spelling takes that line break in place of the last token. A statement that parses leaves the parser on it, so the parser hands over its current token and no longer tracks the last token a source spells. 36 of the fixtures' 5,127 statement sources change, each by gaining the comment its last line ends with, and nothing else in any of their ASTs does. No golden plan held such a comment, so no plan text in the tests or the docs moves. Co-Authored-By: Claude Fable 5.2 --- docs/Pluto IR Plan.md | 9 +++++---- lexer/lexer.go | 15 ++++++++------- lexer/lexer_test.go | 28 ++++++++++++++++------------ parser/parser.go | 16 +++++++--------- parser/scriptparser_test.go | 6 +++--- 5 files changed, 39 insertions(+), 35 deletions(-) diff --git a/docs/Pluto IR Plan.md b/docs/Pluto IR Plan.md index c007794a..3c3181b0 100644 --- a/docs/Pluto IR Plan.md +++ b/docs/Pluto IR Plan.md @@ -741,10 +741,11 @@ A plan's `source` follows the opposite rule, since it is the whole statement rather than an operand: the label stands alone and the statement's own lines sit one level in, so a block literal reads as it is laid out (decided 2026-11-23). What it renders is the file's own text, from the statement's -first token to its last: a comment the statement does not reach is never in -it, while one between two of its own tokens is. Each later line loses the -indentation the statement stands at, which the layout rules give every line -of its own, so the lines keep the shape the file gives them; a line holding +first token to the line break that ends it: a comment any of its lines ends +with is in it, and so is a comment line between two of its lines, while the +lines around the statement are not (decided 2026-11-26). Each later line +loses the indentation the statement stands at, which the layout rules give +every line of its own, so the lines keep the shape the file gives them; a line holding nothing of the statement — blank, or a comment at any indentation — loses no more than it has, and a line a string literal runs through keeps the characters the string holds. So the parens the ast adds diff --git a/lexer/lexer.go b/lexer/lexer.go index 36a51e94..adcf47e8 100644 --- a/lexer/lexer.go +++ b/lexer/lexer.go @@ -91,19 +91,20 @@ func (l *Lexer) createToken(tokenType token.TokenType, literal string, hadSpace } // Spelling is the source a statement is spelled with: the input from first -// to the end of last, so a comment the statement does not reach is never in -// it. Its lines keep the shape the file gives them: each later one loses the +// to end, the line break that ends the statement, so a comment a line of the +// statement ends with is in it and the lines around the statement are not. +// Its lines keep the shape the file gives them: each later one loses the // indentation the statement stands at, which the layout rules give every // line of its own, and a blank or comment line loses what it has of that. A // line a string literal runs into keeps its characters as they are, since // those are what the string holds; literals are the string tokens the -// statement spans, in source order. first and last are tokens this lexer -// produced, each spelling source of its own, first at or before last: no -// other pair names a span of this input, so a caller that hands one over has +// statement spans, in source order. first is a token this lexer produced +// that spells source, and end the line break it produced after it: no other +// pair names a statement of this input, so a caller that hands one over has // a bug that checking here would only move. -func (l *Lexer) Spelling(first, last token.Token, literals []token.Token) string { +func (l *Lexer) Spelling(first, end token.Token, literals []token.Token) string { indent := first.Column - 1 - lines := spanLines(l.input, first.Pos, last.Pos+last.Len, literals) + lines := spanLines(l.input, first.Pos, end.Pos, literals) spelled := make([]string, len(lines)) for i, line := range lines { diff --git a/lexer/lexer_test.go b/lexer/lexer_test.go index fe8d145c..a73d8348 100644 --- a/lexer/lexer_test.go +++ b/lexer/lexer_test.go @@ -1420,12 +1420,12 @@ func TestDecodeStringEscapePhysicalBreak(t *testing.T) { } // spellAll quotes every token of src as one span, as a parser does for a -// statement: from the first token a source spells to the last, with the -// string literals between them. +// statement: from the first token a source spells to the last line break, +// with the string literals between them. func spellAll(t *testing.T, src string) string { t.Helper() l := New("spellAll", src) - var first, last token.Token + var first, end token.Token var literals []token.Token for { tok, err := l.NextToken() @@ -1435,18 +1435,20 @@ func spellAll(t *testing.T, src string) string { if tok.Type == token.EOF { break } + if tok.Type == token.NEWLINE { + end = tok + } if tok.Len == 0 { continue } if first.Len == 0 { first = tok } - last = tok if tok.Type == token.STRING { literals = append(literals, tok) } } - return l.Spelling(first, last, literals) + return l.Spelling(first, end, literals) } // spellFrom quotes the tokens of src from the first one on line from, as a @@ -1454,7 +1456,7 @@ func spellAll(t *testing.T, src string) string { func spellFrom(t *testing.T, src string, from int) string { t.Helper() l := New("spellFrom", src) - var first, last token.Token + var first, end token.Token var literals []token.Token for { tok, err := l.NextToken() @@ -1464,18 +1466,20 @@ func spellFrom(t *testing.T, src string, from int) string { if tok.Type == token.EOF { break } + if tok.Type == token.NEWLINE { + end = tok + } if tok.Len == 0 || tok.Line < from { continue } if first.Len == 0 { first = tok } - last = tok if tok.Type == token.STRING { literals = append(literals, tok) } } - return l.Spelling(first, last, literals) + return l.Spelling(first, end, literals) } // A span an indented statement makes moves left as one: each later line @@ -1504,16 +1508,16 @@ func TestSpellingMovesASpanAsOne(t *testing.T) { } // Spelling quotes a statement as its file spells it: from its first token to -// its last, so a comment it does not reach is never in it, with every later -// line moved left to where the first stands and a line a string literal runs -// through left as the string holds it. +// the line break that ends it, so a comment any of its lines ends with is in +// it, with every later line moved left to where the first stands and a line +// a string literal runs through left as the string holds it. func TestSpelling(t *testing.T) { cases := []struct { name string src string want string }{ - {"OneLineLeavesItsComment", "a = 1 # one\n", "a = 1"}, + {"OneLineKeepsItsCommentWithoutItsBlanks", "a = 1 # one \t\n", "a = 1 # one"}, {"LinesKeepTheirShape", "m = [\n 2 3\n]\n", "m = [\n 2 3\n]"}, {"AnInteriorCommentStays", "m = [\n # a row\n 2 3\n]\n", "m = [\n # a row\n 2 3\n]"}, {"StringContentKeepsItsSpaces", "w = \"hello \n \nworld\"\n", "w = \"hello \n \nworld\""}, diff --git a/parser/parser.go b/parser/parser.go index ebec2b4e..ed9306cd 100644 --- a/parser/parser.go +++ b/parser/parser.go @@ -125,7 +125,6 @@ type StmtParser struct { peekToken token.Token spelling bool // a statement is being parsed, so its tokens are kept stmtStart token.Token // the first token of the statement being parsed - stmtEnd token.Token // the last token of it a source spells stmtLiterals []token.Token // the string literals it spans savedTokens []token.Token // FIFO queue of synthetic tokens from operator splits or inserting a * in something like 9x open brackets // the brackets open where curToken stands @@ -422,11 +421,10 @@ func (p *StmtParser) ParseProgram() *ast.Program { } // noteSpelled keeps what a statement's spelling needs of the token now -// current: the first and last tokens a source spells, and the string literals -// between them, whose characters are the string's own rather than the file's -// layout. Both ends are taken from what a source spells, so neither the -// layout token a statement ends on nor the illegal one a recovered statement -// starts after can reach past it. +// current: the first token a source spells, and the string literals after +// it, whose characters are the string's own rather than the file's layout. +// The start is taken from what a source spells, so the illegal token a +// recovered statement starts after cannot reach before it. func (p *StmtParser) noteSpelled(tok token.Token) { if !p.spelling || tok.Len == 0 { return @@ -434,14 +432,15 @@ func (p *StmtParser) noteSpelled(tok token.Token) { if p.stmtStart.Len == 0 { p.stmtStart = tok } - p.stmtEnd = tok if tok.Type == token.STRING { p.stmtLiterals = append(p.stmtLiterals, tok) } } +// sourceSpelling is the source of the statement that has just ended: +// curToken is the line break it ends on. func (p *StmtParser) sourceSpelling() string { - return p.l.Spelling(p.stmtStart, p.stmtEnd, p.stmtLiterals) + return p.l.Spelling(p.stmtStart, p.curToken, p.stmtLiterals) } // parseStatement parses one statement and gives it the source its file @@ -455,7 +454,6 @@ func (p *StmtParser) parseStatement() ast.Statement { p.spelling = true defer func() { p.spelling = false }() p.stmtStart = token.Token{} - p.stmtEnd = token.Token{} p.stmtLiterals = p.stmtLiterals[:0] p.noteSpelled(firstToken) p.blankIdents = nil // reset for new statement diff --git a/parser/scriptparser_test.go b/parser/scriptparser_test.go index a85f10a2..1a434f13 100644 --- a/parser/scriptparser_test.go +++ b/parser/scriptparser_test.go @@ -55,7 +55,7 @@ func TestAssign(t *testing.T) { // Plan §12: a statement carries the source its file spells it with, so a // plan quotes what its author wrote rather than the ast's own rendering: the // parens the ast adds are absent, an implicit multiplication reads as it was -// typed, a comment the line ends with is cut, and a statement of several +// typed, a comment the line ends with is kept, and a statement of several // lines keeps its own shape dedented to its first line. func TestStatementSpelling(t *testing.T) { const script = `b = ((a)) @@ -78,7 +78,7 @@ world" "b = ((a))", "n = -a", "imp = 5a", - "f = -8 >> 1", + "f = -8 >> 1 # arithmetic right shift", "m = [\n 1 2\n 3 4\n]", "long =\n a + 1", "w = \"hello \n \n\t\nworld\"", @@ -292,7 +292,7 @@ line two" spelled = append(spelled, inner.(*ast.LetStatement).Src) } } - require.Equal(t, []string{"t = x * 2", "s = \"line one\nline two\"", "u =\n# flush left\n x + 1", "v = [\n : Name Score\n \"Ada\" 1\n]", "r = t + 1"}, spelled) + require.Equal(t, []string{"t = x * 2 # doubled", "s = \"line one\nline two\"", "u =\n# flush left\n x + 1", "v = [\n : Name Score\n \"Ada\" 1\n]", "r = t + 1"}, spelled) } func TestInvalidAssignment(t *testing.T) {