Jay Taylor's notes
back to listing indexPlayground
[web search]
Original source (sap.github.io)
Clipped on: 2016-03-11
Parser
Grammar:
1
(function jsonExample() {
2
// ----------------- Lexer -----------------
3
var extendToken = chevrotain.extendToken;
4
var Lexer = chevrotain.Lexer;
5
6
// In ES6, custom inheritance implementation
7
// (such as the one above) can be replaced
8
// with a more simple: "class X extends Y"...
9
var True = extendToken("True", /true/);
10
var False = extendToken("False", /false/);
11
var Null = extendToken("Null", /null/);
12
var LCurly = extendToken("LCurly", /{/);
13
var RCurly = extendToken("RCurly", /}/);
14
var LSquare = extendToken("LSquare", /\[/);
15
var RSquare = extendToken("RSquare", /]/);
16
var Comma = extendToken("Comma", /,/);
17
var Colon = extendToken("Colon", /:/);
18
var StringLiteral = extendToken("StringLiteral",
19
/"(:?[^\\"\n\r]+|\\(:?[bfnrtv"\\/]|u[0-9a-fA-F]{4}))*"/);
20
var NumberLiteral = extendToken("NumberLiteral",
21
/-?(0|[1-9]\d*)(\.\d+)?([eE][+-]?\d+)?/);
22
var WhiteSpace = extendToken("WhiteSpace", /\s+/);
23
WhiteSpace.GROUP = Lexer.SKIPPED;
24
25
26
var jsonTokens = [WhiteSpace, NumberLiteral, StringLiteral, RCurly, LCurly,
27
LSquare, RSquare, Comma, Colon, True, False, Null];
28
29
var ChevJsonLexer = new Lexer(jsonTokens, true);
30
31
// ----------------- parser -----------------
32
var ChevrotainParser = chevrotain.Parser;
33
34
function ChevrotainJsonParser(input) {
35
ChevrotainParser.call(this, input, jsonTokens);
36
var $ = this;
37
38
this.json = this.RULE("json", function () {
39
// @formatter:off
40
return $.OR([
41
{ ALT: function () { return $.SUBRULE($.object) }},
42
{ ALT: function () { return $.SUBRULE($.array) }}
43
]);
44
// @formatter:on
45
});
46
47
this.object = this.RULE("object", function () {
48
// use debugger statements to add breakpoints
49
// (if your browser supports debugging evaluated code)
Input
Sample:
1
{
2
"firstName": "John",
3
"lastName": "Smith",
4
"isAlive": true,
5
"age": 25
6
}
Syntax Diagrams
json
object arrayobject
LCurly objectItem objectItem Comma objectItem objectItem RCurlyobjectItem
StringLiteral Colon valuearray
LSquare value value Comma value value RSquarevalue
StringLiteral NumberLiteral object array True False Null
Output
1
{
2
"firstName": "John",
3
"lastName": "Smith",
4
"isAlive": true,
5
"age": 25
6
}