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/ast/ast.go b/ast/ast.go index 3a7d7574..f1669b89 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; a plan requires one, so a caller that builds a statement sets it too } 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; a plan requires one, so a caller that builds a statement sets it too } func (ps *PrintStatement) statementNode() {} diff --git a/compiler/pir.go b/compiler/pir.go index 89ebaa19..5765c66c 100644 --- a/compiler/pir.go +++ b/compiler/pir.go @@ -380,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: stmt.String()}, + Head: pir.Head{Label: "assign " + strings.Join(nameParts, ", "), Func: fn, Source: stmt.Src}, Commit: make([]pir.Mapping, 0, len(stmt.Name)), } @@ -529,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: stmt.String()}} + 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 962b7db7..4c4fba14 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 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/docs/Pluto Conditional Value Semantics.md b/docs/Pluto Conditional Value Semantics.md index 13514560..38415894 100644 --- a/docs/Pluto Conditional Value Semantics.md +++ b/docs/Pluto Conditional Value Semantics.md @@ -354,6 +354,17 @@ Spacing separates cells, and operators glue their operands into one cell: [a > 3 && b < 5 || 10] # one 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 **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/docs/Pluto IR Plan.md b/docs/Pluto IR Plan.md index 3c179f59..3c3181b0 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,46 @@ 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` -and `advance` carry no mode keyword: both are always simultaneous (§14). +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 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 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 +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 +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 +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 +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 - source "x = ((data[i] || other[j]) || (-1))" + source + x = data[i] || other[j] || -1 execute %t0 = @@ -764,7 +796,8 @@ transfer (decided 2026-11-20). ```text assign v - source "v = ((n > 2) && 10)" + source + v = n > 2 && 10 execute %t0 = @@ -786,7 +819,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 +1442,8 @@ in source order. ```text print - source "\"n: -n\", h, (h ⊕ \"!\")" + source + "n: -n", h, h ⊕ "!" execute %t0 = eval borrowed Str h @@ -1445,7 +1480,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 +1551,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 +1636,8 @@ either way. ```text assign s - source "s = (sarr[9] || h)" + source + s = sarr[9] || h execute %t0 = @@ -1711,7 +1752,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 +1818,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 +1886,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 +1948,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/lexer/lexer.go b/lexer/lexer.go index 6f86b6ca..adcf47e8 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, at any -// depth 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 past the line holding its '['" HEADER_COLON_ERR = "a header's ':' has one space after it, so its names line up with the values" ) @@ -92,7 +90,89 @@ func (l *Lexer) createToken(tokenType token.TokenType, literal string, hadSpace return tok } -// tokenAt makes a token at column on the line being read. +// Spelling is the source a statement is spelled with: the input from first +// 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 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, end token.Token, literals []token.Token) string { + indent := first.Column - 1 + lines := spanLines(l.input, first.Pos, end.Pos, literals) + + spelled := make([]string, len(lines)) + for i, line := range lines { + text := line.text + if !line.beginsInString { + text = text[min(indent, leading(text)):] + } + if !line.endsInString { + text = strings.TrimRight(text, " \t") + } + spelled[i] = text + } + return strings.Join(spelled, "\n") +} + +// 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, 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 + beginsInString bool + endsInString 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 — +// 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++ + } + + 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 < i; j++ { + lit, stop := literals[j].Pos, literals[j].Pos+literals[j].Len + line.beginsInString = line.beginsInString || (start > lit && start < stop) + line.endsInString = line.endsInString || (i > lit && i < stop) + } + lines = append(lines, line) + + if i >= end { + return lines + } + _, start = LogicalRune(input, i) + } +} + +// 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, @@ -100,6 +180,7 @@ func (l *Lexer) tokenAt(tokenType token.TokenType, literal string, column int) t Literal: literal, Line: l.lineOffset, Column: column, + Pos: l.position, } } @@ -115,7 +196,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() } @@ -188,7 +269,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") } @@ -250,14 +331,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 { - 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) @@ -285,6 +366,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 @@ -354,12 +444,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 4bf58674..a73d8348 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}, @@ -1418,3 +1418,164 @@ 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 line break, +// with the string literals between them. +func spellAll(t *testing.T, src string) string { + t.Helper() + l := New("spellAll", src) + var first, end 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.Type == token.NEWLINE { + end = tok + } + if tok.Len == 0 { + continue + } + if first.Len == 0 { + first = tok + } + if tok.Type == token.STRING { + literals = append(literals, tok) + } + } + return l.Spelling(first, end, 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, end 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.Type == token.NEWLINE { + end = tok + } + if tok.Len == 0 || tok.Line < from { + continue + } + if first.Len == 0 { + first = tok + } + if tok.Type == token.STRING { + literals = append(literals, tok) + } + } + return l.Spelling(first, end, literals) +} + +// 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 { + 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]"}, + {"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 +// 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 + }{ + {"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\""}, + {"ADeeperLineKeepsItsShape", "long =\n a + 1\n", "long =\n a + 1"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + if got := spellAll(t, tc.src); got != tc.want { + t.Fatalf("Spelling = %q, want %q", got, tc.want) + } + }) + } +} + +// 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) { + if got, want := spellAll(t, src), "m = [\n 2\n]"; got != want { + t.Fatalf("Spelling = %q, want %q", got, want) + } + }) + } +} + +// 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\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 { + 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: + 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 { + 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/parser/codeparser_test.go b/parser/codeparser_test.go index 47f9ebf2..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) { @@ -274,7 +280,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" @@ -721,3 +726,34 @@ 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. 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) { + 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") + }) + } +} diff --git a/parser/parser.go b/parser/parser.go index 9bb505f4..ed9306cd 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 @@ -96,9 +121,13 @@ type StmtParser struct { l *lexer.Lexer errors []*token.CompileError - curToken token.Token - peekToken token.Token - savedTokens []token.Token // FIFO queue of synthetic tokens from operator splits or inserting a * in something like 9x + 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 + 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 @@ -176,7 +205,10 @@ 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 if len(p.savedTokens) > 0 { @@ -240,105 +272,69 @@ 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 { - if tok.Type != token.OPERATOR { - return []token.Token{tok} - } - - match := p.findLongestOp(tok.Literal, opType) - if match == "" || match == tok.Literal { - return []token.Token{tok} // No split needed - } - - // Split into matched part and remainder - result := []token.Token{ - { - Type: token.OPERATOR, - Literal: match, - FileName: tok.FileName, - Line: tok.Line, - Column: tok.Column, - // Preserve source spacing so attached-prefix boundary checks still - // work after an operator run is split into parseable pieces. - HadSpace: tok.HadSpace, - }, +// 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 +} - 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 + utf8.RuneCountInString(match), - }) - } +// 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) + first := tok + first.Literal = match + first.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, PrefixOp) - 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:]...) - } - queue = append(queue, originalPeek) - 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 + 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 } - // Replace peek with matched part, queue the rest - p.peekToken = tokens[0] - p.savedTokens = append(tokens[1:], 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 { @@ -392,6 +388,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, @@ -419,11 +420,42 @@ func (p *StmtParser) ParseProgram() *ast.Program { return program } +// noteSpelled keeps what a statement's spelling needs of the token now +// 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 + } + if p.stmtStart.Len == 0 { + p.stmtStart = 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.curToken, 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() ast.Statement { if p.skipIndented() { return nil } firstToken := p.curToken + p.spelling = true + defer func() { p.spelling = false }() + p.stmtStart = token.Token{} + 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 @@ -438,6 +470,7 @@ func (p *StmtParser) parseStatement() ast.Statement { p.errorOnBlanks() return &ast.PrintStatement{ Token: firstToken, + Src: p.sourceSpelling(), Expression: &ast.CallExpression{ Token: firstToken, Function: &ast.Identifier{Token: firstToken, Value: ""}, @@ -460,8 +493,9 @@ func (p *StmtParser) parseStatement() ast.Statement { } p.checkNoDuplicates(identList) - if stmt := p.parseLetStatement(identList); stmt != nil { - return stmt + if let := p.parseLetStatement(identList); let != nil { + let.Src = p.sourceSpelling() + return let } return nil } @@ -691,7 +725,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) { @@ -891,7 +925,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 } @@ -930,7 +965,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. @@ -960,11 +1022,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 @@ -1141,7 +1198,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" @@ -1200,8 +1257,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() @@ -1211,6 +1268,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 @@ -1265,11 +1323,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}) } } @@ -1503,17 +1561,23 @@ 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. +// 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 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) } + if p.open.squares < start.squares { + break + } if !p.atLineEnd() { p.nextToken() } @@ -1526,6 +1590,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 { @@ -1664,7 +1741,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 05361e35..1a434f13 100644 --- a/parser/scriptparser_test.go +++ b/parser/scriptparser_test.go @@ -1,6 +1,7 @@ package parser import ( + "fmt" "strings" "testing" @@ -51,6 +52,249 @@ 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 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)) +n = -a +imp = 5a +f = -8 >> 1 # arithmetic right shift +m = [ + 1 2 + 3 4 +] +long = + a + 1 +w = "hello + + +world" +"out: -b -n" +` + want := []string{ + "b = ((a))", + "n = -a", + "imp = 5a", + "f = -8 >> 1 # arithmetic right shift", + "m = [\n 1 2\n 3 4\n]", + "long =\n a + 1", + "w = \"hello \n \n\t\nworld\"", + `"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) + } + } +} + +// 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 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, "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 +// 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") +} + +// 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)) + first, remainder := splitOperator(p.curToken, "√") + + runes := []rune(script) + 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() + } +} + +// 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 +// 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, 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 +// 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", + "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) { + 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" + u = +# flush left + x + 1 + v = [ + : Name Score + "Ada" 1 + ] + 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 # 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) { tests := []struct { name string @@ -82,16 +326,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", }}, } @@ -671,6 +915,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. @@ -1635,14 +1892,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}}, @@ -1658,6 +1916,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}, @@ -1806,6 +2065,37 @@ 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, 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" + 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}}, + {"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() + + 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) { @@ -1903,9 +2193,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()) } diff --git a/pir/pir_test.go b/pir/pir_test.go index 63e7da9e..ac203fad 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] @@ -1528,18 +1551,66 @@ func TestRenderSkip(t *testing.T) { } } +// 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. +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() @@ -1548,7 +1619,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..5c40172f 100644 --- a/pir/print.go +++ b/pir/print.go @@ -3,7 +3,6 @@ package pir import ( "fmt" "slices" - "strconv" "strings" "unicode" @@ -98,10 +97,21 @@ 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 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 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(logicalNewlines(head.Source), "\n") { + if line == "" { + b.WriteString("\n") + continue + } + fmt.Fprintf(b, " %s\n", escapeControls(line)) + } b.WriteString("\n execute\n") } @@ -168,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 } } @@ -194,24 +206,38 @@ 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, 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 + } + 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 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 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() 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 }