-
Notifications
You must be signed in to change notification settings - Fork 1
/
parser.js
52 lines (44 loc) · 1.4 KB
/
parser.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
var parserState = {
grammar: '',
document: '',
shouldTrace: false
}
function parseRaw() {
let parser
const shouldTrace = parserState.shouldTrace
try {
parser = peg.generate( parserState.grammar, { cache: true, trace: shouldTrace } )
} catch (e) {
return {parsed: "", trace: JSON.stringify( e, null, 2 ) }
}
const blanker = function() { return 'No trace compiled' }
const tracer = shouldTrace
? new Tracer( parserState.document, { showTrace: false, useColor: false } )
: { getParseTreeString: blanker, getBacktraceString: blanker }
let parsed, trace
try {
parsed = parser.parse( parserState.document, { tracer } )
trace = tracer.getParseTreeString()
} catch (e) {
parsed = e
trace = tracer.getBacktraceString()
}
return { parsed: JSON.stringify( parsed, null, 2 ), trace: JSON.stringify( trace, null, 2 ) }
}
var parseTimer = null
function parse( grammar, document, shouldTrace, sendBack ) {
parserState.grammar = grammar;
parserState.document = document;
parserState.shouldTrace = shouldTrace;
if ( parseTimer ) {
return;
}
parseTimer = window.setTimeout( function() {
parseTimer = null;
tic = Date.now();
var result = parseRaw();
toc = Date.now();
console.log( '%cParse took ' + ( toc - tic ) + 'ms', 'color: red' );
sendBack( result );
}, shouldTrace ? 150 : 50 );
}