-
Notifications
You must be signed in to change notification settings - Fork 3
/
parser.ts
70 lines (62 loc) · 1.68 KB
/
parser.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
// parser
// ======
import * as types from '../common/types'
import { toStrict } from './encoding'
import {
parse as peggyParse,
SyntaxError as peggySyntaxError,
} from './tibasic.peggy'
/**
* @alpha
*/
export interface ParseOptions {
sourceMap?: string
}
/**
* @alpha
*/
export function parse (source: string, options: ParseOptions = {}): types.Line[] {
const sourceMap = options.sourceMap ?? 'inline'
// TODO:
// * Allow multiple statements per line with ':'
const sourceLines = source.split(/\r?\n/)
const parsedLines = sourceLines.map((s: string): types.Line => {
const sourceLine = toStrict(s)
let parsedLine: types.Statement
try {
parsedLine = peggyParse(sourceLine)
} catch (error: unknown) {
if (error instanceof peggySyntaxError) {
parsedLine = { type: types.TiSyntaxError }
} else {
throw error
}
}
return {
statement: parsedLine,
source: sourceMap === 'inline' ? sourceLine : undefined,
}
})
return parsedLines
}
export function parseExpression (source: string): types.ValueExpression {
const sourceLines = source.split(/\r?\n/)
if (sourceLines.length > 1) {
throw new Error('Too many lines for an expression')
}
const sourceLine = sourceLines[0]
if (sourceLine === undefined) {
throw new Error('Too few lines for an expression')
}
let parsedLine: types.Statement
try {
parsedLine = peggyParse(sourceLine)
} catch (error: unknown) {
if (error instanceof peggySyntaxError) {
parsedLine = { type: types.TiSyntaxError }
} else {
throw error
}
}
return parsedLine.type === types.ValueStatement ? parsedLine.value : { type: types.TiSyntaxError }
}