package gololang_test import ( "strings" "testing" "rickub.com/turbo-editors/turbo-core/syntax" "rickub.com/turbo-editors/turbo-golo/internal/gololang" ) // coloured is one span with the text it covers, which is what a test wants to // talk about: "the word function is a keyword", not "columns 0 to 8 are class // 1". type coloured struct { text string class syntax.Class } func (c coloured) String() string { return c.text + ":" + c.class.String() } // colouredLine returns every span of one line of source, with its text. func colouredLine(t *testing.T, src string) []coloured { t.Helper() lines := gololang.Highlight(src) if len(lines) != 1 { t.Fatalf("Highlight(%q) returned %d lines, want 1", src, len(lines)) } return withText([]rune(src), lines[0]) } // withText pairs each span with the runes it covers. func withText(line []rune, spans []syntax.Span) []coloured { out := make([]coloured, 0, len(spans)) for _, span := range spans { out = append(out, coloured{string(line[span.Start:span.End]), span.Class}) } return out } // find returns the span covering exactly the given text, if there is one. func find(spans []coloured, text string) (coloured, bool) { for _, span := range spans { if span.text == text { return span, true } } return coloured{}, false } // assertClass fails unless one span covers exactly text and has the wanted // class. Asking for the whole text means a scanner that split a construct in // two is caught, not only one that coloured it wrongly. func assertClass(t *testing.T, src, text string, want syntax.Class) { t.Helper() spans := colouredLine(t, src) got, ok := find(spans, text) if !ok { t.Fatalf("in %q: no single span covers %q; got %v", src, text, spans) } if got.class != want { t.Errorf("in %q: %q is %s, want %s", src, text, got.class, want) } } // lineOf returns the spans of one line of a multi-line document, with text. func lineOf(src string, number int) []coloured { lines := strings.Split(src, "\n") return withText([]rune(lines[number]), gololang.Highlight(src)[number]) } // --- the three invariants the editor relies on ------------------------------ // A representative body of Golo, used by the invariant tests below. It is // deliberately a mixture: every construct the scanner knows, some broken // input, and the constructs that most easily run into one another. const sample = `#!/usr/bin/env golo module demo.Shapes import gololang.Errors ---- A block comment, with --- near misses and a "quote" inside it. ---- struct Point = { x, y } union Shape = { Circle = { radius } Rect = { width, height } } augment Shape$Circle { function area = |this| -> 3.14159 * this: radius() * this: radius() } function main = |args| { let p = Point(1, 2) var big = 42L let ratio = 2.5e-3F let text = """ a multi-line "string" """ let label = match { when p: x() > 0 then "positive" otherwise "other" } foreach i in range(0, 3) { println("i = " + i + '\n') } let ok = p?: x() orIfNull 0 let 😀 = list[1, 2, 3] let broken = "unterminated let after = 1 }` func TestEveryLineGetsExactlyOneEntry(t *testing.T) { // The editor indexes the result by line number without checking, so a // scanner that returned one entry fewer would draw every line below the // gap in the wrong colours. src := sample + "\n\n\ntrailing\n" want := len(strings.Split(src, "\n")) if got := len(gololang.Highlight(src)); got != want { t.Errorf("Highlight returned %d lines for %d lines of source", got, want) } } func TestSpansAreInOrderAndDoNotOverlap(t *testing.T) { // Spans are drawn in the order they arrive. Two out of order paint over // each other, and nothing fails. for number, spans := range gololang.Highlight(sample) { line := []rune(strings.Split(sample, "\n")[number]) previousEnd := 0 for _, span := range spans { switch { case span.Start < previousEnd: t.Errorf("line %d: span %v starts before the previous one ended at %d", number+1, span, previousEnd) case span.Start >= span.End: t.Errorf("line %d: span %v is empty or inverted", number+1, span) case span.End > len(line): t.Errorf("line %d: span %v runs past the %d runes of the line", number+1, span, len(line)) } previousEnd = span.End } } } func TestBrokenInputStillColours(t *testing.T) { // Source under the cursor is invalid most of the time it is being typed. broken := []string{ `let x = "`, `let x = '`, `let x = "\`, `"""`, `""`, `----`, `---`, `-----`, `#`, `function`, `function (`, `module`, `import a.`, `.`, `..`, `1.`, `1e`, `1e-`, `$`, `}}}`, `|`, `->`, `?:`, } for _, src := range broken { spans := gololang.Highlight(src) if len(spans) != 1 { t.Errorf("Highlight(%q) returned %d lines, want 1", src, len(spans)) } } } func TestAnEmptyDocumentIsOneEmptyLine(t *testing.T) { if got := gololang.Highlight(""); len(got) != 1 || len(got[0]) != 0 { t.Errorf("Highlight(\"\") = %v, want one line with no spans", got) } } func TestCRLFColoursTheSameAsLF(t *testing.T) { unix := gololang.Highlight("function main = |args| {\n println(\"hi\")\n}") windows := gololang.Highlight("function main = |args| {\r\n println(\"hi\")\r\n}") if len(unix) != len(windows) { t.Fatalf("CRLF gave %d lines, LF gave %d", len(windows), len(unix)) } for i := range unix { if len(unix[i]) != len(windows[i]) { t.Errorf("line %d: CRLF gave %v, LF gave %v", i+1, windows[i], unix[i]) } } } // --- what crosses a line break ---------------------------------------------- func TestABlockCommentIsCarriedToItsClosingDashes(t *testing.T) { src := "let a = 1 ----\nstill a comment\n---- let b = 2\nlet c = 3" if got, ok := find(lineOf(src, 1), "still a comment"); !ok || got.class != syntax.ClassComment { t.Errorf("the line inside a block comment is %v, want all comment", lineOf(src, 1)) } third := lineOf(src, 2) if got, ok := find(third, "----"); !ok || got.class != syntax.ClassComment { t.Errorf("the closing dashes are %v, want a comment", third) } if got, ok := find(third, "let"); !ok || got.class != syntax.ClassKeyword { t.Errorf("code after the closing dashes is %v, want a keyword", third) } if got, ok := find(lineOf(src, 3), "let"); !ok || got.class != syntax.ClassKeyword { t.Errorf("the line after the comment is %v, want code", lineOf(src, 3)) } } func TestThreeDashesDoNotCloseABlockComment(t *testing.T) { // The lexer asks for four dashes. Three inside a comment are its text, and // the tree-sitter grammar's own test — "with --- near misses" — is the // same case. src := "----\nwith --- near misses\nlet x = 1 ----\nlet y = 2" if got, ok := find(lineOf(src, 2), "let x = 1 ----"); !ok || got.class != syntax.ClassComment { t.Errorf("a line inside the comment after a near miss is %v, want all comment", lineOf(src, 2)) } if got, ok := find(lineOf(src, 3), "let"); !ok || got.class != syntax.ClassKeyword { t.Errorf("the line after the comment is %v, want code", lineOf(src, 3)) } } func TestAStringIsCarriedToItsClosingQuote(t *testing.T) { // The interpreter reads a string to its closing quote and stops at // nothing in between, so the colour follows it. This is the decision the // other scanners in the family make the other way, for languages whose // grammar forbids the newline; Golo's lexer does not. src := "let s = \"first line\nsecond line\nthird\" + rest\nlet next = 1" if got, ok := find(lineOf(src, 1), "second line"); !ok || got.class != syntax.ClassString { t.Errorf("the middle of a multi-line string is %v, want all string", lineOf(src, 1)) } third := lineOf(src, 2) if got, ok := find(third, `third"`); !ok || got.class != syntax.ClassString { t.Errorf("the end of the string is %v, want string up to the quote", third) } if got, ok := find(third, "rest"); !ok || got.class != syntax.ClassIdentifier { t.Errorf("code after the closing quote is %v, want a name", third) } if got, ok := find(lineOf(src, 3), "let"); !ok || got.class != syntax.ClassKeyword { t.Errorf("the line after the string is %v, want code", lineOf(src, 3)) } } func TestATripleQuotedStringIsCarriedToItsClosingQuotes(t *testing.T) { src := "let s = \"\"\"\na \"quoted\" line # not a comment\n\"\"\" + rest\nlet next = 1" second := lineOf(src, 1) if len(second) != 1 || second[0].class != syntax.ClassString { t.Errorf("a line inside a triple-quoted string is %v, want one string span", second) } third := lineOf(src, 2) if got, ok := find(third, `"""`); !ok || got.class != syntax.ClassString { t.Errorf("the closing quotes are %v, want string", third) } if got, ok := find(third, "rest"); !ok || got.class != syntax.ClassIdentifier { t.Errorf("code after the closing quotes is %v, want a name", third) } } func TestACharacterLiteralIsCarriedLikeAString(t *testing.T) { // The same loop in lexer.go reads both, so a stray apostrophe paints to // the next apostrophe, wherever that is. src := "let c = 'x\nstill' + 1" if got, ok := find(lineOf(src, 1), "still'"); !ok || got.class != syntax.ClassChar { t.Errorf("the continuation of a character literal is %v, want char", lineOf(src, 1)) } if got, ok := find(lineOf(src, 1), "1"); !ok || got.class != syntax.ClassNumber { t.Errorf("code after the closing apostrophe is %v, want a number", lineOf(src, 1)) } } func TestAnEscapedQuoteAtTheEndOfALineKeepsTheStringOpen(t *testing.T) { // A backslash before the newline escapes it, and the lexer keeps reading. src := "let s = \"ends with a slash \\\nand goes on\"\nlet next = 1" if got, ok := find(lineOf(src, 1), `and goes on"`); !ok || got.class != syntax.ClassString { t.Errorf("after an escaped newline the string is %v, want string", lineOf(src, 1)) } } func TestALineCommentEndsAtTheLine(t *testing.T) { src := "# a comment\nlet x = 1" if got, ok := find(lineOf(src, 1), "let"); !ok || got.class != syntax.ClassKeyword { t.Errorf("the line after a # comment is %v, want code", lineOf(src, 1)) } } // --- one case per construct ------------------------------------------------- func TestConstructs(t *testing.T) { cases := []struct { name string src string text string class syntax.Class }{ {"line comment", `let x = 1 # why`, `# why`, syntax.ClassComment}, {"shebang", `#!/usr/bin/env golo`, `#!/usr/bin/env golo`, syntax.ClassComment}, {"block comment on one line", `let x = 1 ---- why ---- + 2`, `---- why ----`, syntax.ClassComment}, {"code after a one-line block comment", `let x = 1 ---- why ---- + 2`, `2`, syntax.ClassNumber}, {"empty block comment", `--------`, `--------`, syntax.ClassComment}, {"hash inside a string is not a comment", `let s = "# not a comment"`, `"# not a comment"`, syntax.ClassString}, {"dashes inside a string are not a comment", `let s = "---- not a comment ----"`, `"---- not a comment ----"`, syntax.ClassString}, {"string", `let s = "hi"`, `"hi"`, syntax.ClassString}, {"string stops at its closing quote", `let s = "hi" + name`, `"hi"`, syntax.ClassString}, {"code after a string is still code", `let s = "hi" + name`, `name`, syntax.ClassIdentifier}, {"empty string", `let s = ""`, `""`, syntax.ClassString}, {"string with an escaped quote", `let s = "he said \"hi\""`, `"he said \"hi\""`, syntax.ClassString}, {"string with a hex escape", `let s = "\x41"`, `"\x41"`, syntax.ClassString}, {"triple-quoted string on one line", `let s = """a "b" c""" + d`, `"""a "b" c"""`, syntax.ClassString}, {"code after a triple-quoted string", `let s = """a "b" c""" + d`, `d`, syntax.ClassIdentifier}, {"char literal", `let c = 'x'`, `'x'`, syntax.ClassChar}, {"escaped char literal", `let c = '\n'`, `'\n'`, syntax.ClassChar}, {"char stops at its closing quote", `let c = 'x' + 1`, `1`, syntax.ClassNumber}, {"integer", `let n = 42`, `42`, syntax.ClassNumber}, {"long", `let n = 42L`, `42L`, syntax.ClassNumber}, {"double", `let n = 3.14`, `3.14`, syntax.ClassNumber}, {"float with a capital suffix", `let n = 3.14F`, `3.14F`, syntax.ClassNumber}, {"float with a small suffix", `let n = 2.0f`, `2.0f`, syntax.ClassNumber}, {"exponent", `let n = 1.5e3`, `1.5e3`, syntax.ClassNumber}, {"negative exponent", `let n = 1.5e-3`, `1.5e-3`, syntax.ClassNumber}, {"integer with an exponent", `let n = 2E10`, `2E10`, syntax.ClassNumber}, {"minus is an operator, not part of the number", `let n = -1`, `-`, syntax.ClassOperator}, {"keyword", `function main = |args| {`, `function`, syntax.ClassKeyword}, {"local keyword", `local function helper = |x| -> x`, `local`, syntax.ClassKeyword}, {"word operator", `let ok = a and b`, `and`, syntax.ClassKeyword}, {"orIfNull", `let v = x orIfNull 0`, `orIfNull`, syntax.ClassKeyword}, {"oftype", `if x oftype String.class {`, `oftype`, syntax.ClassKeyword}, {"match", `let l = match {`, `match`, syntax.ClassKeyword}, {"when then otherwise", ` when x then "y"`, `then`, syntax.ClassKeyword}, {"constant true", `let ok = true`, `true`, syntax.ClassConstant}, {"constant null", `let n = null`, `null`, syntax.ClassConstant}, {"builtin", `println("hi")`, `println`, syntax.ClassBuiltin}, {"builtin collection literal", `let xs = list[1, 2]`, `list`, syntax.ClassBuiltin}, {"builtin spelt like a type", `let o = DynamicObject()`, `DynamicObject`, syntax.ClassBuiltin}, {"builtin range", `foreach i in range(0, 3) {`, `range`, syntax.ClassBuiltin}, {"declared function", `function main = |args| {`, `main`, syntax.ClassFunction}, {"declared function with an arrow body", `function twice = |x| -> x * 2`, `twice`, syntax.ClassFunction}, {"declared emoji function", `function 🚀launch = {`, `🚀launch`, syntax.ClassFunction}, {"call", `helper(1)`, `helper`, syntax.ClassFunction}, {"method call after a colon", `this: radius()`, `radius`, syntax.ClassFunction}, {"plain identifier", `let shape = other`, `other`, syntax.ClassIdentifier}, {"emoji identifier", `let 😀 = 1`, `😀`, syntax.ClassIdentifier}, {"accented identifier", `let été = 1`, `été`, syntax.ClassIdentifier}, {"CJK identifier", `let 名前 = 1`, `名前`, syntax.ClassIdentifier}, {"underscore identifier", `let _hidden = 1`, `_hidden`, syntax.ClassIdentifier}, {"struct name", `struct Point = { x, y }`, `Point`, syntax.ClassType}, {"union name", `union Shape = {`, `Shape`, syntax.ClassType}, {"variant", ` Circle = { radius }`, `Circle`, syntax.ClassType}, {"constructor call", `let p = Point(1, 2)`, `Point`, syntax.ClassType}, {"variant constructor", `let r = Result_Failure("no")`, `Result_Failure`, syntax.ClassType}, {"augment target", `augment Person {`, `Person`, syntax.ClassType}, {"union variant separator", `augment Shape$Circle {`, `$`, syntax.ClassPunctuation}, {"module path", `module hello.World`, `hello.World`, syntax.ClassType}, {"import path", `import gololang.Errors`, `gololang.Errors`, syntax.ClassType}, {"three-part import path", `import java.util.List`, `java.util.List`, syntax.ClassType}, {"closure bars", `let f = |x| -> x`, `|`, syntax.ClassOperator}, {"arrow", `let f = |x| -> x`, `->`, syntax.ClassOperator}, {"colon", `this: name()`, `:`, syntax.ClassOperator}, {"safe navigation", `let n = p?: x()`, `?:`, syntax.ClassOperator}, {"comparison", `if a <= b {`, `<=`, syntax.ClassOperator}, {"not equal", `if a != b {`, `!=`, syntax.ClassOperator}, {"range operator", `let r = 1..3`, `..`, syntax.ClassOperator}, {"range does not swallow the number", `let r = 1..3`, `1`, syntax.ClassNumber}, {"variadic dots", `function f = |args...| {`, `...`, syntax.ClassOperator}, {"module dot outside a path", `let x = a.b`, `.`, syntax.ClassPunctuation}, {"brace", `function main = |args| {`, `{`, syntax.ClassPunctuation}, {"bracket", `let xs = list[1]`, `[`, syntax.ClassPunctuation}, {"comma", `struct Point = { x, y }`, `,`, syntax.ClassPunctuation}, } for _, c := range cases { t.Run(c.name, func(t *testing.T) { assertClass(t, c.src, c.text, c.class) }) } } // --- one case per thing the scanner deliberately refuses -------------------- func TestRefusals(t *testing.T) { cases := []struct { name string why string src string text string class syntax.Class }{ { name: "no digit separators", why: "the lexer has none, so 1_000 is the number 1 followed by the name _000", src: `let n = 1_000`, text: `1`, class: syntax.ClassNumber, }, { name: "no hexadecimal", why: "the lexer has none, so 0xFF is the number 0 followed by the name xFF", src: `let n = 0xFF`, text: `xFF`, class: syntax.ClassIdentifier, }, { name: "a leading dot is never a number", why: "the lexer requires a digit before the point, so .5 is a dot and then a number", src: `let n = .5`, text: `.`, class: syntax.ClassPunctuation, }, { name: "a lower-case l is not a long suffix", why: "the lexer accepts only the upper-case L, so 42l is 42 and then the name l", src: `let n = 42l`, text: `42`, class: syntax.ClassNumber, }, { name: "three dashes are an operator run", why: "the lexer asks for four dashes to open a comment; three are two minus signs and a third", src: `let x = a --- b`, text: `---`, class: syntax.ClassOperator, }, { name: "a constructor of your own is a type", why: "nothing in the syntax separates Circle(1.0) from a type applied to arguments", src: `let c = Circle(1.0)`, text: `Circle`, class: syntax.ClassType, }, { name: "Some is not a constant", why: "in Golo it is a variant of an ordinary union declared in gololang.Errors, not a builtin", src: `let s = Some(1)`, text: `Some`, class: syntax.ClassType, }, { name: "a capitalised variable is a type", why: "the case rule is a convention, and the scanner follows the convention rather than the parser", src: `let Count = 1`, text: `Count`, class: syntax.ClassType, }, { name: "a keyword used as a method name stays a keyword", why: "the scanner does not track what a colon introduces, and the lexer would refuse the word anyway", src: `obj: match()`, text: `match`, class: syntax.ClassKeyword, }, { name: "a module path stops at a dot with nothing after it", why: "half-typed `import a.` leaves the dot as punctuation rather than swallowing it", src: `import a.`, text: `.`, class: syntax.ClassPunctuation, }, { name: "a string nothing closes runs to the end of the line and beyond", why: "the interpreter reads to the closing quote wherever it is, so the colour follows it", src: `let s = "oops`, text: `"oops`, class: syntax.ClassString, }, { name: "no escapes inside a triple-quoted string", why: "the lexer appends every rune until the three quotes, so a backslash-quote does not protect them", src: `let s = """a\""" + b`, text: `"""a\"""`, class: syntax.ClassString, }, } for _, c := range cases { t.Run(c.name, func(t *testing.T) { assertClass(t, c.src, c.text, c.class) }) } } func TestAnUnterminatedStringPaintsTheNextLine(t *testing.T) { // The other half of the carry decision, stated as what a user sees: the // line after a stray quote is coloured as string, because that is what // the interpreter will read it as. src := "let broken = \"unterminated\nlet after = 1" if got, ok := find(lineOf(src, 1), "let after = 1"); !ok || got.class != syntax.ClassString { t.Errorf("the line after an unterminated string is %v, want all string", lineOf(src, 1)) } } func TestTheDeclaredNameAfterFunctionIsAFunctionEvenWhenNoParenthesisFollows(t *testing.T) { // Everywhere else a name is a function because a parenthesis follows it. // A declaration is followed by an equals sign, and is the one place a // reader most wants the colour. spans := colouredLine(t, `function main = |args| {`) got, ok := find(spans, "main") if !ok || got.class != syntax.ClassFunction { t.Errorf("the declared name is %v, want a function; got %v", got, spans) } if got, ok := find(spans, "args"); !ok || got.class != syntax.ClassIdentifier { t.Errorf("the parameter is %v, want a plain name", got) } } func TestTheKeywordTableIsEveryReservedWordButTheLiterals(t *testing.T) { // token/token.go in GoloScript reserves 41 words. Three of them are the // literal values, which are constants here; the other 38 are keywords. keywords := gololang.Keywords() if len(keywords) != 38 { t.Errorf("the scanner knows %d keywords, want 38", len(keywords)) } for _, literal := range []string{"true", "false", "null"} { for _, keyword := range keywords { if keyword == literal { t.Errorf("%q is in the keyword table; it is a constant", literal) } } } } func TestTheBuiltinTableHoldsWhatTheInterpreterProvides(t *testing.T) { // evaluator.BuiltinNames() answers 162 names, five of which begin with a // double underscore and are the test runner's own counters. A test in // editor_test.go holds this table to a real golo when one is installed; // this one holds its shape when none is. builtins := gololang.Builtins() if len(builtins) != 157 { t.Errorf("the scanner knows %d builtins, want 157", len(builtins)) } seen := map[string]bool{} for _, name := range builtins { if strings.HasPrefix(name, "__") { t.Errorf("%q is an internal helper and should not be coloured as a builtin", name) } if seen[name] { t.Errorf("%q is listed twice", name) } seen[name] = true } } func TestHighlightIsWhatTheRegistryUses(t *testing.T) { gololang.Register() spans := syntax.Highlight(gololang.Language, "function main = |args| {\n") if len(spans) == 0 || len(spans[0]) == 0 { t.Fatalf("syntax.Highlight gave nothing for Golo: %v", spans) } if spans[0][0].Class != syntax.ClassKeyword { t.Errorf("the registered highlighter coloured function as %s, want a keyword", spans[0][0].Class) } }