-
Notifications
You must be signed in to change notification settings - Fork 0
/
tokenize.js
65 lines (58 loc) · 1.56 KB
/
tokenize.js
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
"use strict";
import fs from "node:fs";
import parser from "@babel/parser";
export function tokenize(filename, printDebug = false) {
const sourceCode = fs.readFileSync(filename, { encoding: "utf8" });
const ast = parser.parse(sourceCode, {
// copied from Package Analysis babel-parser.js
errorRecovery: true,
sourceType: "unambiguous",
tokens: true
})
const tokenValues = [];
let lastEndPos = 0;
let lastLine = 1;
for (let t of ast.tokens) {
// check if there was whitespace since last token
if (t.loc.start.line > lastLine) {
tokenValues.push("nl");
lastEndPos++;
}
lastLine = t.loc.end.line;
if (t.start > lastEndPos) {
tokenValues.push("sp");
}
lastEndPos = t.end;
let value;
if (t.value === undefined) {
// syntax marker (e.g bracket, dot)
value = t.type.label;
} else if (t.type.label === "string" || t.type.label === "template") {
// quote string
// TODO escape quotes in string
value = `'${t.value}'`
} else {
// anything else
value = t.value;
}
tokenValues.push(value);
}
if (printDebug) {
console.log(ast.tokens);
console.log(sourceCode);
console.log(tokenValues);
}
return tokenValues;
}
// formats the list of tokens returned by tokenize() into a
// Python list of strings
export function formatTokens(tokens, includeSpace) {
const tokenList = [];
for (let t of tokens) {
if (t === "sp" && !includeSpace) {
continue;
}
tokenList.push(`"${t}"`)
}
return "[" + tokenList.join(", ") + "]";
}