1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
|
package rustlang
import (
"strings"
"testing"
"rickub.com/turbo-editors/turbo-core/syntax"
)
// classAt returns the class covering a rune column on a line, and whether any
// span covers it at all. It is how nearly every test below asks its question.
func classAt(spans [][]syntax.Span, line, col int) (syntax.Class, bool) {
if line < 0 || line >= len(spans) {
return 0, false
}
for _, s := range spans[line] {
if col >= s.Start && col < s.End {
return s.Class, true
}
}
return 0, false
}
// classOfFirst returns the class of the first occurrence of word in src.
func classOfFirst(t *testing.T, src, word string) syntax.Class {
t.Helper()
index := strings.Index(src, word)
if index < 0 {
t.Fatalf("%q does not appear in the source", word)
}
line := strings.Count(src[:index], "\n")
col := index - (strings.LastIndex(src[:index], "\n") + 1)
class, ok := classAt(Highlight(src), line, col)
if !ok {
t.Fatalf("no span covers %q at line %d column %d", word, line, col)
}
return class
}
func TestHighlightReturnsOneEntryPerLine(t *testing.T) {
// The editor indexes the result by line number without checking, so a short
// result is an index out of range in the middle of a redraw.
tests := []struct {
name string
src string
want int
}{
{"empty", "", 1},
{"one line without a terminator", "fn main() {}", 1},
{"one line with a terminator", "fn main() {}\n", 2},
{"three lines", "a\nb\nc", 3},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
if got := len(Highlight(tc.src)); got != tc.want {
t.Errorf("Highlight(%q) returned %d lines, want %d", tc.src, got, tc.want)
}
})
}
}
func TestEachTokenClass(t *testing.T) {
const src = `use std::fmt;
// a comment
/// a doc comment
struct Point {
x: i32,
}
fn main() {
let name = "world";
let initial = 'w';
let count = 42;
let ratio = 1.5;
println!("hello {name}");
}
`
tests := []struct {
word string
want syntax.Class
}{
{"use", syntax.ClassKeyword},
{"struct", syntax.ClassKeyword},
{"fn", syntax.ClassKeyword},
{"let", syntax.ClassKeyword},
{"// a comment", syntax.ClassComment},
{"/// a doc comment", syntax.ClassComment},
{"Point", syntax.ClassType},
{"i32", syntax.ClassType},
{`"world"`, syntax.ClassString},
{"'w'", syntax.ClassChar},
{"42", syntax.ClassNumber},
{"1.5", syntax.ClassNumber},
{"println!", syntax.ClassBuiltin},
{"::", syntax.ClassPunctuation},
}
for _, test := range tests {
t.Run(test.word, func(t *testing.T) {
if got := classOfFirst(t, src, test.word); got != test.want {
t.Errorf("%q is %v, want %v", test.word, got, test.want)
}
})
}
}
func TestADeclaredFunctionNameIsAFunction(t *testing.T) {
if got := classOfFirst(t, "fn parse(input: &str) {}", "parse"); got != syntax.ClassFunction {
t.Errorf("parse is %v, want function", got)
}
}
func TestACallIsAFunction(t *testing.T) {
if got := classOfFirst(t, "let n = compute(3);", "compute"); got != syntax.ClassFunction {
t.Errorf("compute is %v, want function", got)
}
}
func TestAnUpperCaseNameIsAType(t *testing.T) {
// Rust's naming convention is strong enough to lean on: a type, a trait and
// an enum variant are all UpperCamelCase, and nothing else is.
for _, word := range []string{"HashMap", "Display", "MyError"} {
src := "let x: " + word + " = todo();"
if got := classOfFirst(t, src, word); got != syntax.ClassType {
t.Errorf("%s is %v, want type", word, got)
}
}
}
func TestALowerCaseNameIsAPlainIdentifier(t *testing.T) {
if got := classOfFirst(t, "let total = subtotal + tax;", "subtotal"); got != syntax.ClassIdentifier {
t.Errorf("subtotal is %v, want identifier", got)
}
}
func TestAPrimitiveTypeOutranksTheCallHeuristic(t *testing.T) {
// u8::from_str_radix has a "(" after it eventually, but u8 is a type.
if got := classOfFirst(t, "let n = u8::MAX;", "u8"); got != syntax.ClassType {
t.Errorf("u8 is %v, want type", got)
}
}
func TestSelfAndCapitalSelfAreTypes(t *testing.T) {
const src = "impl Point {\n fn x(&self) -> Self { *self }\n}"
if got := classOfFirst(t, src, "self"); got != syntax.ClassType {
t.Errorf("self is %v, want type", got)
}
if got := classOfFirst(t, src, "Self"); got != syntax.ClassType {
t.Errorf("Self is %v, want type", got)
}
}
func TestTheLiteralsAreConstants(t *testing.T) {
for _, word := range []string{"true", "false", "None", "Some", "Ok", "Err"} {
src := "let v = " + word + ";"
if got := classOfFirst(t, src, word); got != syntax.ClassConstant {
t.Errorf("%s is %v, want constant", word, got)
}
}
}
func TestAMacroTakesItsExclamationMarkWithIt(t *testing.T) {
// println! is one name; colouring the ! separately would read as a negation.
spans := Highlight(`println!("hi");`)
class, ok := classAt(spans, 0, 7) // the "!"
if !ok || class != syntax.ClassBuiltin {
t.Errorf("the ! of println! is %v (covered: %v), want builtin", class, ok)
}
}
func TestNotEqualsIsNotAMacro(t *testing.T) {
// `a != b` has a ! straight after a word, and is not a macro invocation.
if got := classOfFirst(t, "if a != b {}", "a"); got == syntax.ClassBuiltin {
t.Error("a != b was read as a macro call")
}
}
func TestAnAttributeIsColouredAsOne(t *testing.T) {
tests := []string{"#[derive(Debug)]", "#![no_std]", "#[cfg(test)]"}
for _, src := range tests {
t.Run(src, func(t *testing.T) {
spans := Highlight(src + "\nstruct S;")
for col := 0; col < len(src); col++ {
class, ok := classAt(spans, 0, col)
if !ok || class != syntax.ClassAttribute {
t.Fatalf("column %d of %q is %v (covered: %v), want attribute", col, src, class, ok)
}
}
})
}
}
func TestCodeAfterAnAttributeIsStillCode(t *testing.T) {
spans := Highlight("#[derive(Debug)] struct S;")
class, ok := classAt(spans, 0, strings.Index("#[derive(Debug)] struct S;", "struct"))
if !ok || class != syntax.ClassKeyword {
t.Errorf("struct after an attribute is %v (covered: %v), want keyword", class, ok)
}
}
func TestBlockCommentsNest(t *testing.T) {
// Rust nests them, so a flag instead of a depth would end this comment at
// the first */ and colour the rest of the line as code.
const src = "/* outer /* inner */ still a comment */ let x = 1;"
spans := Highlight(src)
commentEnd := strings.Index(src, "*/ let") + 2
for col := 0; col < commentEnd; col++ {
class, ok := classAt(spans, 0, col)
if !ok || class != syntax.ClassComment {
t.Fatalf("column %d is %v (covered: %v), want comment", col, class, ok)
}
}
if got := classOfFirst(t, src, "let"); got != syntax.ClassKeyword {
t.Errorf("the code after the comment is %v, want keyword", got)
}
}
func TestABlockCommentCarriesAcrossLines(t *testing.T) {
spans := Highlight("/* one\ntwo\n*/ let x = 1;")
for line := range 2 {
class, ok := classAt(spans, line, 0)
if !ok || class != syntax.ClassComment {
t.Errorf("line %d is %v (covered: %v), want comment", line, class, ok)
}
}
class, ok := classAt(spans, 2, 3) // the "l" of let
if !ok || class != syntax.ClassKeyword {
t.Errorf("the code after the comment is %v (covered: %v), want keyword", class, ok)
}
}
func TestANestedCommentCarriesItsDepthAcrossLines(t *testing.T) {
spans := Highlight("/* a\n/* b\n*/ still\n*/ let x = 1;")
// Line 2 closes only the inner comment, so it is still a comment.
class, ok := classAt(spans, 2, 3)
if !ok || class != syntax.ClassComment {
t.Errorf("line 2 is %v (covered: %v); the outer comment was closed too early", class, ok)
}
class, ok = classAt(spans, 3, 3)
if !ok || class != syntax.ClassKeyword {
t.Errorf("line 3 is %v (covered: %v), want the code after the comment", class, ok)
}
}
func TestRawStringsAreColouredToTheirHashes(t *testing.T) {
const src = `let re = r#"a "quoted" thing"#;`
spans := Highlight(src)
// The quote in the middle must not end the string.
class, ok := classAt(spans, 0, strings.Index(src, `"quoted"`))
if !ok || class != syntax.ClassString {
t.Errorf("the inner quote is %v (covered: %v), want string", class, ok)
}
if got := classOfFirst(t, src, ";"); got != syntax.ClassPunctuation {
t.Errorf("the semicolon after the raw string is %v, want punctuation", got)
}
}
func TestARawStringCarriesAcrossLines(t *testing.T) {
spans := Highlight("let q = r#\"select\nfrom t\n\"#;\nlet x = 1;")
class, ok := classAt(spans, 1, 0)
if !ok || class != syntax.ClassString {
t.Errorf("the second line of the raw string is %v (covered: %v), want string", class, ok)
}
class, ok = classAt(spans, 3, 0)
if !ok || class != syntax.ClassKeyword {
t.Errorf("the line after the raw string is %v (covered: %v), want code", class, ok)
}
}
func TestARawStringWithNoHashesEndsAtItsQuote(t *testing.T) {
const src = `let s = r"plain"; let n = 1;`
if got := classOfFirst(t, src, "let n"); got != syntax.ClassKeyword {
t.Errorf("the code after r\"plain\" is %v, want keyword", got)
}
}
func TestAnOrdinaryStringMayCrossALine(t *testing.T) {
// Rust allows a real newline inside "…", so this is not an error state.
spans := Highlight("let s = \"one\ntwo\";\nlet x = 1;")
class, ok := classAt(spans, 1, 0)
if !ok || class != syntax.ClassString {
t.Errorf("the second line of the string is %v (covered: %v), want string", class, ok)
}
class, ok = classAt(spans, 2, 0)
if !ok || class != syntax.ClassKeyword {
t.Errorf("the line after the string is %v (covered: %v), want code", class, ok)
}
}
func TestAnEscapedQuoteDoesNotEndAString(t *testing.T) {
const src = `let s = "a \" b"; let n = 1;`
if got := classOfFirst(t, src, "let n"); got != syntax.ClassKeyword {
t.Errorf("the code after an escaped quote is %v, want keyword", got)
}
}
func TestByteStringsAndByteCharacters(t *testing.T) {
if got := classOfFirst(t, `let b = b"bytes";`, `b"bytes"`); got != syntax.ClassString {
t.Errorf(`b"bytes" is %v, want string`, got)
}
if got := classOfFirst(t, `let c = b'x';`, `b'x'`); got != syntax.ClassChar {
t.Errorf(`b'x' is %v, want char`, got)
}
}
func TestALifetimeIsNotACharacterLiteral(t *testing.T) {
// They begin with the same rune, and getting this wrong strings the rest of
// the line: 'a is a lifetime, 'a' is a character.
const src = "fn longest<'a>(x: &'a str) -> &'a str { x }"
class, ok := classAt(Highlight(src), 0, strings.Index(src, "'a>"))
if !ok || class == syntax.ClassChar || class == syntax.ClassString {
t.Errorf("the lifetime 'a is %v (covered: %v), want it not read as a literal", class, ok)
}
// The code after it must survive, which is the failure that actually hurts.
if got := classOfFirst(t, src, "str"); got != syntax.ClassType {
t.Errorf("str after two lifetimes is %v, want type", got)
}
}
func TestStaticIsALifetimeToo(t *testing.T) {
const src = "let s: &'static str = \"hi\";"
if got := classOfFirst(t, src, `"hi"`); got != syntax.ClassString {
t.Errorf("the string after 'static is %v, want string; the lifetime swallowed it", got)
}
}
func TestAnEscapedCharacterIsStillACharacter(t *testing.T) {
for _, literal := range []string{`'\n'`, `'\''`, `'\u{1F600}'`} {
src := "let c = " + literal + "; let n = 1;"
t.Run(literal, func(t *testing.T) {
if got := classOfFirst(t, src, literal); got != syntax.ClassChar {
t.Errorf("%s is %v, want char", literal, got)
}
if got := classOfFirst(t, src, "let n"); got != syntax.ClassKeyword {
t.Errorf("the code after %s is %v, want keyword", literal, got)
}
})
}
}
func TestNumbersTakeTheirSeparatorsPrefixesAndSuffixes(t *testing.T) {
tests := []string{"1_000", "0xFF", "0b1010", "0o77", "1.5e-3", "42u8", "3.0f64"}
for _, literal := range tests {
t.Run(literal, func(t *testing.T) {
src := "let n = " + literal + ";"
spans := Highlight(src)
start := strings.Index(src, literal)
for col := start; col < start+len(literal); col++ {
class, ok := classAt(spans, 0, col)
if !ok || class != syntax.ClassNumber {
t.Fatalf("column %d of %q is %v (covered: %v), want the whole literal to be a number", col-start, literal, class, ok)
}
}
})
}
}
func TestARangeIsNotADecimalPoint(t *testing.T) {
// `0..10` is two numbers and a range operator, not one strange number.
const src = "for i in 0..10 {}"
spans := Highlight(src)
class, ok := classAt(spans, 0, strings.Index(src, ".."))
if !ok || class != syntax.ClassOperator {
t.Errorf("the .. of a range is %v (covered: %v), want operator", class, ok)
}
}
func TestSpansNeverStraddleALineBreak(t *testing.T) {
spans := Highlight("/* a\nb */\nfn main() {}")
for line, onLine := range spans {
for _, span := range onLine {
if span.Start < 0 || span.End < span.Start {
t.Errorf("line %d holds a nonsense span %+v", line, span)
}
}
}
}
func TestSpansOnALineAreOrderedAndDoNotOverlap(t *testing.T) {
// The editor draws them in order and assumes they do not overlap.
const src = `fn f(x: &'a str) -> Option<u8> { Some(b"hi"[0]) }`
for line, onLine := range Highlight(src) {
previousEnd := 0
for _, span := range onLine {
if span.Start < previousEnd {
t.Errorf("line %d: span %+v starts before the previous one ended at %d", line, span, previousEnd)
}
previousEnd = span.End
}
}
}
func TestBrokenSourceIsStillColoured(t *testing.T) {
// Source under the cursor is invalid most of the time it is being typed.
tests := []string{
`let s = "unterminated`,
"fn f( {",
"let x = 'unterminated",
"#[derive(",
"r#\"unterminated",
}
for _, src := range tests {
t.Run(src, func(t *testing.T) {
spans := Highlight(src)
if len(spans) != 1 {
t.Fatalf("Highlight(%q) returned %d lines, want 1", src, len(spans))
}
})
}
}
func TestColumnsAreCountedInRunesNotBytes(t *testing.T) {
// A byte offset would put the spans of a line with an accent in it out of
// step with what is drawn.
const src = `let café = "thé";`
spans := Highlight(src)
// "thé" starts at rune column 12: l-e-t-space-c-a-f-é-space-=-space-"
class, ok := classAt(spans, 0, 12)
if !ok || class != syntax.ClassString {
t.Errorf("the string after an accented identifier is %v (covered: %v), want string", class, ok)
}
}
func TestAWholeFileOfRustColoursWithoutPanicking(t *testing.T) {
// A broad sweep over the constructs the scanner knows, run for its own
// sake: the classes are checked one at a time above.
const src = `//! A module doc comment.
use std::collections::HashMap;
/// Adds two numbers.
#[derive(Debug, Clone)]
pub struct Adder<'a> {
name: &'a str,
seen: HashMap<String, u64>,
}
impl<'a> Adder<'a> {
pub fn new(name: &'a str) -> Self {
Self { name, seen: HashMap::new() }
}
pub fn add(&mut self, a: i64, b: i64) -> Result<i64, String> {
let sql = r#"insert into "log" values (?)"#;
println!("{sql} {} {}", a, b);
match a.checked_add(b) {
Some(v) => Ok(v),
None => Err(format!("overflow: {a} + {b}")),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_adds() {
assert_eq!(Adder::new("x").add(1, 2).unwrap(), 3);
}
}
`
spans := Highlight(src)
if got, want := len(spans), strings.Count(src, "\n")+1; got != want {
t.Fatalf("Highlight() returned %d lines, want %d", got, want)
}
}
|