Debian Codegraph @

examples/json.pegjs

raw
1 /*
2 * JSON Grammar
3 * ============
4 *
5 * Based on the grammar from RFC 7159 [1].
6 *
7 * Note that JSON is also specified in ECMA-262 [2], ECMA-404 [3], and on the
8 * JSON website [4] (somewhat informally). The RFC seems the most authoritative
9 * source, which is confirmed e.g. by [5].
10 *
11 * [1] http://tools.ietf.org/html/rfc7159
12 * [2] http://www.ecma-international.org/publications/standards/Ecma-262.htm
13 * [3] http://www.ecma-international.org/publications/standards/Ecma-404.htm
14 * [4] http://json.org/
15 * [5] https://www.tbray.org/ongoing/When/201x/2014/03/05/RFC7159-JSON
16 */
17
18 /* ----- 2. JSON Grammar ----- */
19
20 JSON_text
21 = ws value:value ws { return value; }
22
23 begin_array = ws "[" ws
24 begin_object = ws "{" ws
25 end_array = ws "]" ws
26 end_object = ws "}" ws
27 name_separator = ws ":" ws
28 value_separator = ws "," ws
29
30 ws "whitespace" = [ \t\n\r]*
31
32 /* ----- 3. Values ----- */
33
34 value
35 = false
36 / null
37 / true
38 / object
39 / array
40 / number
41 / string
42
43 false = "false" { return false; }
44 null = "null" { return null; }
45 true = "true" { return true; }
46
47 /* ----- 4. Objects ----- */
48
49 object
50 = begin_object
51 members:(
52 head:member
53 tail:(value_separator m:member { return m; })*
54 {
55 var result = {}, i;
56
57 result[head.name] = head.value;
58
59 for (i = 0; i < tail.length; i++) {
60 result[tail[i].name] = tail[i].value;
61 }
62
63 return result;
64 }
65 )?
66 end_object
67 { return members !== null ? members: {}; }
68
69 member
70 = name:string name_separator value:value {
71 return { name: name, value: value };
72 }
73
74 /* ----- 5. Arrays ----- */
75
76 array
77 = begin_array
78 values:(
79 head:value
80 tail:(value_separator v:value { return v; })*
81 { return [head].concat(tail); }
82 )?
83 end_array
84 { return values !== null ? values : []; }
85
86 /* ----- 6. Numbers ----- */
87
88 number "number"
89 = minus? int frac? exp? { return parseFloat(text()); }
90
91 decimal_point = "."
92 digit1_9 = [1-9]
93 e = [eE]
94 exp = e (minus / plus)? DIGIT+
95 frac = decimal_point DIGIT+
96 int = zero / (digit1_9 DIGIT*)
97 minus = "-"
98 plus = "+"
99 zero = "0"
100
101 /* ----- 7. Strings ----- */
102
103 string "string"
104 = quotation_mark chars:char* quotation_mark { return chars.join(""); }
105
106 char
107 = unescaped
108 / escape
109 sequence:(
110 '"'
111 / "\\"
112 / "/"
113 / "b" { return "\b"; }
114 / "f" { return "\f"; }
115 / "n" { return "\n"; }
116 / "r" { return "\r"; }
117 / "t" { return "\t"; }
118 / "u" digits:$(HEXDIG HEXDIG HEXDIG HEXDIG) {
119 return String.fromCharCode(parseInt(digits, 16));
120 }
121 )
122 { return sequence; }
123
124 escape = "\\"
125 quotation_mark = '"'
126 unescaped = [^\0-\x1F\x22\x5C]
127
128 /* ----- Core ABNF Rules ----- */
129
130 /* See RFC 4234, Appendix B (http://tools.ietf.org/html/rfc4627). */
131 DIGIT = [0-9]
132 HEXDIG = [0-9a-f]i