|
| 1 | +import assert from 'node:assert/strict' |
| 2 | +import { test } from 'node:test' |
| 3 | +import { |
| 4 | + initialLineState, |
| 5 | + TokenMap, |
| 6 | + tokenizeLine, |
| 7 | +} from '../src/tokenizeTypeScript.js' |
| 8 | + |
| 9 | +const tokenize = (source) => { |
| 10 | + let state = structuredClone(initialLineState) |
| 11 | + return source.split('\n').map((line) => { |
| 12 | + state = tokenizeLine(line, state) |
| 13 | + const tokens = [] |
| 14 | + let offset = 0 |
| 15 | + for (let index = 0; index < state.tokens.length; index += 2) { |
| 16 | + const type = TokenMap[state.tokens[index]] |
| 17 | + const length = state.tokens[index + 1] |
| 18 | + tokens.push([type, line.slice(offset, offset + length)]) |
| 19 | + offset += length |
| 20 | + } |
| 21 | + assert.equal(offset, line.length) |
| 22 | + return tokens |
| 23 | + }) |
| 24 | +} |
| 25 | + |
| 26 | +test('recovers after a standalone new and a following line comment', () => { |
| 27 | + const lines = tokenize( |
| 28 | + `const instance = new \n// constructor to be added\nconst later = new Float32Array(9)` |
| 29 | + ) |
| 30 | + |
| 31 | + assert.ok( |
| 32 | + lines[0].some(([type, text]) => type === 'KeywordNew' && text === 'new') |
| 33 | + ) |
| 34 | + assert.ok( |
| 35 | + lines[1].some(([type, text]) => type === 'Comment' && text.startsWith('//')) |
| 36 | + ) |
| 37 | + assert.ok( |
| 38 | + lines[2].some(([type, text]) => type === 'VariableName' && text === 'later') |
| 39 | + ) |
| 40 | + assert.ok( |
| 41 | + lines[2].some(([type, text]) => type === 'Class' && text === 'Float32Array') |
| 42 | + ) |
| 43 | +}) |
| 44 | + |
| 45 | +test('recovers after an incomplete constructor name', () => { |
| 46 | + const lines = tokenize( |
| 47 | + `const instance = new Floa\n// finish the constructor\nconst later = 1` |
| 48 | + ) |
| 49 | + |
| 50 | + assert.ok( |
| 51 | + lines[0].some(([type, text]) => type === 'Class' && text === 'Floa') |
| 52 | + ) |
| 53 | + assert.ok( |
| 54 | + lines[1].some(([type, text]) => type === 'Comment' && text.startsWith('//')) |
| 55 | + ) |
| 56 | + assert.ok( |
| 57 | + lines[2].some(([type, text]) => type === 'VariableName' && text === 'later') |
| 58 | + ) |
| 59 | +}) |
| 60 | + |
| 61 | +test('keeps constructor continuation after a comment following new', () => { |
| 62 | + const lines = tokenize( |
| 63 | + `const instance = new\n// constructor continues below\nFloat32Array(9)` |
| 64 | + ) |
| 65 | + |
| 66 | + assert.ok( |
| 67 | + lines[2].some(([type, text]) => type === 'Class' && text === 'Float32Array') |
| 68 | + ) |
| 69 | +}) |
0 commit comments