/
gram-parser-plugin.ts
54 lines (47 loc) · 1.39 KB
/
gram-parser-plugin.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
import { ParserFunction, Plugin } from 'unified';
// import {Node as UnistNode} from 'unist';
import { VFile } from 'vfile';
import nearley from 'nearley';
import grammar from './gram-grammar';
import * as errors from './gram-errors';
import { Point } from 'unist';
import { LexerState } from 'nearley';
import { Token } from 'moo';
const lexerLocation = (state: LexerState): Point => {
return {
line: state.line,
column: state.col,
};
};
const tokenLocation = (token: Token) => {
return {
line: token.line,
column: token.col,
};
};
export const parse: ParserFunction = (text: string, file: VFile) => {
const nearleyParser = new nearley.Parser(
nearley.Grammar.fromCompiled(grammar)
);
try {
const parsed = nearleyParser.feed(text);
if (parsed.results[0] === undefined && parsed.lexerState) {
const location = lexerLocation(parsed.lexerState);
file.fail(errors.INCOMPLETE_PARSE, location);
}
if (parsed.results.length > 1) {
file.info('[WARN] parsing is ambiguous');
}
return parsed.results[0] || { type: 'error' };
} catch (e) {
const location = e.token ? tokenLocation(e.token) : { line: 0, column: 0 };
file.fail(e.message, location);
}
};
export interface GramParserSettings {
strict: boolean;
}
const gramParserPlugin: Plugin<GramParserSettings[]> = function() {
this.Parser = parse;
};
export default gramParserPlugin;