-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathparser.ts
More file actions
49 lines (41 loc) · 1.09 KB
/
Copy pathparser.ts
File metadata and controls
49 lines (41 loc) · 1.09 KB
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
import type { CodeStatement, Parse, SimpleToken } from '../types'
import { createProgramNode } from '../utils'
export class Parser {
ast = createProgramNode()
current = 0
constructor(public tokens: SimpleToken[], public parsers: Parse[] = []) {
}
walk() {
const token = this.tokens[this.current]
if (token.type === 'code') {
this.current++
return {
type: 'CodeStatement',
value: token.value,
start: token.start,
end: token.end,
} as CodeStatement
}
for (const parser of this.parsers) {
const node = parser.bind(this)(token)
if (node) {
return {
comment: token.comment,
start: token.start,
end: token.end,
...node,
}
}
}
throw new Error(`Parser: Unknown token type: ${token.type}`)
}
private parse() {
while (this.current < this.tokens.length)
this.ast.body.push(this.walk())
return this.ast
}
static parse(tokens: SimpleToken[], parsers: Parse[] = []) {
const parser = new Parser(tokens, parsers)
return parser.parse()
}
}