-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlex.ts
72 lines (62 loc) · 1.85 KB
/
lex.ts
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
import { Id, Token } from './header.ts';
// lex with regular languages
// deno-fmt-ignore
const MATCH = new RegExp(
'(\\s+)' // whitespace ignored
+ '|(#[^\\n]+)' // comment until end of line ignored
+ '|(\\()' // lparen
+ '|(\\))' // rparen
+ '|(\\[)' // lbrack
+ '|(\\])' // rbrack
+ '|(true|false)' // boolean
+ '|([0-9]+)' // integer
+ '|([-\\+a-z*/=<>]+)' // name: define, + - * / == != < > TODO: add more
+ '|(.)', // BAD
'y'); // sticky bit for exec()
export function lex(s: string) {
let tokens: Token[] = [];
let pos = 0;
while (true) {
let m = MATCH.exec(s);
if (m === null) {
tokens.push({ id: 'eof', start: pos, len: 0, source: s });
break;
}
pos = m.index;
let id: Id | null = null;
let len = -1;
if (m[1] !== undefined) {
// ignore whitespace
} else if (m[2] !== undefined) {
// ignore comment
} else if (m[3] !== undefined) {
id = 'lparen';
} else if (m[4] !== undefined) {
id = 'rparen';
} else if (m[5] !== undefined) {
id = 'lbrack';
} else if (m[6] !== undefined) {
id = 'rbrack';
} else if (m[7] !== undefined) {
id = 'bool';
// no length needed, parser looks at first char 't' or 'f'
} else if (m[8] !== undefined) {
id = 'int';
len = m[8].length;
} else if (m[9] !== undefined) {
id = 'name';
len = m[9].length;
} else if (m[10] !== undefined) {
id = 'BAD';
} else {
throw Error('should not happen');
}
if (id !== null) {
tokens.push({ id, start: pos, len, source: s });
}
// Set pos to end position of last token, so a potential EOF token will
// blame the right column position
pos = MATCH.lastIndex;
}
return tokens;
}