• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/*global Buffer*/
2// Named constants with unique integer values
3var C = {};
4// Tokens
5var LEFT_BRACE    = C.LEFT_BRACE    = 0x1;
6var RIGHT_BRACE   = C.RIGHT_BRACE   = 0x2;
7var LEFT_BRACKET  = C.LEFT_BRACKET  = 0x3;
8var RIGHT_BRACKET = C.RIGHT_BRACKET = 0x4;
9var COLON         = C.COLON         = 0x5;
10var COMMA         = C.COMMA         = 0x6;
11var TRUE          = C.TRUE          = 0x7;
12var FALSE         = C.FALSE         = 0x8;
13var NULL          = C.NULL          = 0x9;
14var STRING        = C.STRING        = 0xa;
15var NUMBER        = C.NUMBER        = 0xb;
16// Tokenizer States
17var START   = C.START   = 0x11;
18var STOP    = C.STOP    = 0x12;
19var TRUE1   = C.TRUE1   = 0x21;
20var TRUE2   = C.TRUE2   = 0x22;
21var TRUE3   = C.TRUE3   = 0x23;
22var FALSE1  = C.FALSE1  = 0x31;
23var FALSE2  = C.FALSE2  = 0x32;
24var FALSE3  = C.FALSE3  = 0x33;
25var FALSE4  = C.FALSE4  = 0x34;
26var NULL1   = C.NULL1   = 0x41;
27var NULL2   = C.NULL2   = 0x42;
28var NULL3   = C.NULL3   = 0x43;
29var NUMBER1 = C.NUMBER1 = 0x51;
30var NUMBER3 = C.NUMBER3 = 0x53;
31var STRING1 = C.STRING1 = 0x61;
32var STRING2 = C.STRING2 = 0x62;
33var STRING3 = C.STRING3 = 0x63;
34var STRING4 = C.STRING4 = 0x64;
35var STRING5 = C.STRING5 = 0x65;
36var STRING6 = C.STRING6 = 0x66;
37// Parser States
38var VALUE   = C.VALUE   = 0x71;
39var KEY     = C.KEY     = 0x72;
40// Parser Modes
41var OBJECT  = C.OBJECT  = 0x81;
42var ARRAY   = C.ARRAY   = 0x82;
43// Character constants
44var BACK_SLASH =      "\\".charCodeAt(0);
45var FORWARD_SLASH =   "\/".charCodeAt(0);
46var BACKSPACE =       "\b".charCodeAt(0);
47var FORM_FEED =       "\f".charCodeAt(0);
48var NEWLINE =         "\n".charCodeAt(0);
49var CARRIAGE_RETURN = "\r".charCodeAt(0);
50var TAB =             "\t".charCodeAt(0);
51
52var STRING_BUFFER_SIZE = 64 * 1024;
53
54function Parser() {
55  this.tState = START;
56  this.value = undefined;
57
58  this.string = undefined; // string data
59  this.stringBuffer = Buffer.alloc ? Buffer.alloc(STRING_BUFFER_SIZE) : new Buffer(STRING_BUFFER_SIZE);
60  this.stringBufferOffset = 0;
61  this.unicode = undefined; // unicode escapes
62  this.highSurrogate = undefined;
63
64  this.key = undefined;
65  this.mode = undefined;
66  this.stack = [];
67  this.state = VALUE;
68  this.bytes_remaining = 0; // number of bytes remaining in multi byte utf8 char to read after split boundary
69  this.bytes_in_sequence = 0; // bytes in multi byte utf8 char to read
70  this.temp_buffs = { "2": new Buffer(2), "3": new Buffer(3), "4": new Buffer(4) }; // for rebuilding chars split before boundary is reached
71
72  // Stream offset
73  this.offset = -1;
74}
75
76// Slow code to string converter (only used when throwing syntax errors)
77Parser.toknam = function (code) {
78  var keys = Object.keys(C);
79  for (var i = 0, l = keys.length; i < l; i++) {
80    var key = keys[i];
81    if (C[key] === code) { return key; }
82  }
83  return code && ("0x" + code.toString(16));
84};
85
86var proto = Parser.prototype;
87proto.onError = function (err) { throw err; };
88proto.charError = function (buffer, i) {
89  this.tState = STOP;
90  this.onError(new Error("Unexpected " + JSON.stringify(String.fromCharCode(buffer[i])) + " at position " + i + " in state " + Parser.toknam(this.tState)));
91};
92proto.appendStringChar = function (char) {
93  if (this.stringBufferOffset >= STRING_BUFFER_SIZE) {
94    this.string += this.stringBuffer.toString('utf8');
95    this.stringBufferOffset = 0;
96  }
97
98  this.stringBuffer[this.stringBufferOffset++] = char;
99};
100proto.appendStringBuf = function (buf, start, end) {
101  var size = buf.length;
102  if (typeof start === 'number') {
103    if (typeof end === 'number') {
104      if (end < 0) {
105        // adding a negative end decreeses the size
106        size = buf.length - start + end;
107      } else {
108        size = end - start;
109      }
110    } else {
111      size = buf.length - start;
112    }
113  }
114
115  if (size < 0) {
116    size = 0;
117  }
118
119  if (this.stringBufferOffset + size > STRING_BUFFER_SIZE) {
120    this.string += this.stringBuffer.toString('utf8', 0, this.stringBufferOffset);
121    this.stringBufferOffset = 0;
122  }
123
124  buf.copy(this.stringBuffer, this.stringBufferOffset, start, end);
125  this.stringBufferOffset += size;
126};
127proto.write = function (buffer) {
128  if (typeof buffer === "string") buffer = new Buffer(buffer);
129  var n;
130  for (var i = 0, l = buffer.length; i < l; i++) {
131    if (this.tState === START){
132      n = buffer[i];
133      this.offset++;
134      if(n === 0x7b){ this.onToken(LEFT_BRACE, "{"); // {
135      }else if(n === 0x7d){ this.onToken(RIGHT_BRACE, "}"); // }
136      }else if(n === 0x5b){ this.onToken(LEFT_BRACKET, "["); // [
137      }else if(n === 0x5d){ this.onToken(RIGHT_BRACKET, "]"); // ]
138      }else if(n === 0x3a){ this.onToken(COLON, ":");  // :
139      }else if(n === 0x2c){ this.onToken(COMMA, ","); // ,
140      }else if(n === 0x74){ this.tState = TRUE1;  // t
141      }else if(n === 0x66){ this.tState = FALSE1;  // f
142      }else if(n === 0x6e){ this.tState = NULL1; // n
143      }else if(n === 0x22){ // "
144        this.string = "";
145        this.stringBufferOffset = 0;
146        this.tState = STRING1;
147      }else if(n === 0x2d){ this.string = "-"; this.tState = NUMBER1; // -
148      }else{
149        if (n >= 0x30 && n < 0x40) { // 1-9
150          this.string = String.fromCharCode(n); this.tState = NUMBER3;
151        } else if (n === 0x20 || n === 0x09 || n === 0x0a || n === 0x0d) {
152          // whitespace
153        } else {
154          return this.charError(buffer, i);
155        }
156      }
157    }else if (this.tState === STRING1){ // After open quote
158      n = buffer[i]; // get current byte from buffer
159      // check for carry over of a multi byte char split between data chunks
160      // & fill temp buffer it with start of this data chunk up to the boundary limit set in the last iteration
161      if (this.bytes_remaining > 0) {
162        for (var j = 0; j < this.bytes_remaining; j++) {
163          this.temp_buffs[this.bytes_in_sequence][this.bytes_in_sequence - this.bytes_remaining + j] = buffer[j];
164        }
165
166        this.appendStringBuf(this.temp_buffs[this.bytes_in_sequence]);
167        this.bytes_in_sequence = this.bytes_remaining = 0;
168        i = i + j - 1;
169      } else if (this.bytes_remaining === 0 && n >= 128) { // else if no remainder bytes carried over, parse multi byte (>=128) chars one at a time
170        if (n <= 193 || n > 244) {
171          return this.onError(new Error("Invalid UTF-8 character at position " + i + " in state " + Parser.toknam(this.tState)));
172        }
173        if ((n >= 194) && (n <= 223)) this.bytes_in_sequence = 2;
174        if ((n >= 224) && (n <= 239)) this.bytes_in_sequence = 3;
175        if ((n >= 240) && (n <= 244)) this.bytes_in_sequence = 4;
176        if ((this.bytes_in_sequence + i) > buffer.length) { // if bytes needed to complete char fall outside buffer length, we have a boundary split
177          for (var k = 0; k <= (buffer.length - 1 - i); k++) {
178            this.temp_buffs[this.bytes_in_sequence][k] = buffer[i + k]; // fill temp buffer of correct size with bytes available in this chunk
179          }
180          this.bytes_remaining = (i + this.bytes_in_sequence) - buffer.length;
181          i = buffer.length - 1;
182        } else {
183          this.appendStringBuf(buffer, i, i + this.bytes_in_sequence);
184          i = i + this.bytes_in_sequence - 1;
185        }
186      } else if (n === 0x22) {
187        this.tState = START;
188        this.string += this.stringBuffer.toString('utf8', 0, this.stringBufferOffset);
189        this.stringBufferOffset = 0;
190        this.onToken(STRING, this.string);
191        this.offset += Buffer.byteLength(this.string, 'utf8') + 1;
192        this.string = undefined;
193      }
194      else if (n === 0x5c) {
195        this.tState = STRING2;
196      }
197      else if (n >= 0x20) { this.appendStringChar(n); }
198      else {
199          return this.charError(buffer, i);
200      }
201    }else if (this.tState === STRING2){ // After backslash
202      n = buffer[i];
203      if(n === 0x22){ this.appendStringChar(n); this.tState = STRING1;
204      }else if(n === 0x5c){ this.appendStringChar(BACK_SLASH); this.tState = STRING1;
205      }else if(n === 0x2f){ this.appendStringChar(FORWARD_SLASH); this.tState = STRING1;
206      }else if(n === 0x62){ this.appendStringChar(BACKSPACE); this.tState = STRING1;
207      }else if(n === 0x66){ this.appendStringChar(FORM_FEED); this.tState = STRING1;
208      }else if(n === 0x6e){ this.appendStringChar(NEWLINE); this.tState = STRING1;
209      }else if(n === 0x72){ this.appendStringChar(CARRIAGE_RETURN); this.tState = STRING1;
210      }else if(n === 0x74){ this.appendStringChar(TAB); this.tState = STRING1;
211      }else if(n === 0x75){ this.unicode = ""; this.tState = STRING3;
212      }else{
213        return this.charError(buffer, i);
214      }
215    }else if (this.tState === STRING3 || this.tState === STRING4 || this.tState === STRING5 || this.tState === STRING6){ // unicode hex codes
216      n = buffer[i];
217      // 0-9 A-F a-f
218      if ((n >= 0x30 && n < 0x40) || (n > 0x40 && n <= 0x46) || (n > 0x60 && n <= 0x66)) {
219        this.unicode += String.fromCharCode(n);
220        if (this.tState++ === STRING6) {
221          var intVal = parseInt(this.unicode, 16);
222          this.unicode = undefined;
223          if (this.highSurrogate !== undefined && intVal >= 0xDC00 && intVal < (0xDFFF + 1)) { //<56320,57343> - lowSurrogate
224            this.appendStringBuf(new Buffer(String.fromCharCode(this.highSurrogate, intVal)));
225            this.highSurrogate = undefined;
226          } else if (this.highSurrogate === undefined && intVal >= 0xD800 && intVal < (0xDBFF + 1)) { //<55296,56319> - highSurrogate
227            this.highSurrogate = intVal;
228          } else {
229            if (this.highSurrogate !== undefined) {
230              this.appendStringBuf(new Buffer(String.fromCharCode(this.highSurrogate)));
231              this.highSurrogate = undefined;
232            }
233            this.appendStringBuf(new Buffer(String.fromCharCode(intVal)));
234          }
235          this.tState = STRING1;
236        }
237      } else {
238        return this.charError(buffer, i);
239      }
240    } else if (this.tState === NUMBER1 || this.tState === NUMBER3) {
241        n = buffer[i];
242
243        switch (n) {
244          case 0x30: // 0
245          case 0x31: // 1
246          case 0x32: // 2
247          case 0x33: // 3
248          case 0x34: // 4
249          case 0x35: // 5
250          case 0x36: // 6
251          case 0x37: // 7
252          case 0x38: // 8
253          case 0x39: // 9
254          case 0x2e: // .
255          case 0x65: // e
256          case 0x45: // E
257          case 0x2b: // +
258          case 0x2d: // -
259            this.string += String.fromCharCode(n);
260            this.tState = NUMBER3;
261            break;
262          default:
263            this.tState = START;
264            var result = Number(this.string);
265
266            if (isNaN(result)){
267              return this.charError(buffer, i);
268            }
269
270            if ((this.string.match(/[0-9]+/) == this.string) && (result.toString() != this.string)) {
271              // Long string of digits which is an ID string and not valid and/or safe JavaScript integer Number
272              this.onToken(STRING, this.string);
273            } else {
274              this.onToken(NUMBER, result);
275            }
276
277            this.offset += this.string.length - 1;
278            this.string = undefined;
279            i--;
280            break;
281        }
282    }else if (this.tState === TRUE1){ // r
283      if (buffer[i] === 0x72) { this.tState = TRUE2; }
284      else { return this.charError(buffer, i); }
285    }else if (this.tState === TRUE2){ // u
286      if (buffer[i] === 0x75) { this.tState = TRUE3; }
287      else { return this.charError(buffer, i); }
288    }else if (this.tState === TRUE3){ // e
289      if (buffer[i] === 0x65) { this.tState = START; this.onToken(TRUE, true); this.offset+= 3; }
290      else { return this.charError(buffer, i); }
291    }else if (this.tState === FALSE1){ // a
292      if (buffer[i] === 0x61) { this.tState = FALSE2; }
293      else { return this.charError(buffer, i); }
294    }else if (this.tState === FALSE2){ // l
295      if (buffer[i] === 0x6c) { this.tState = FALSE3; }
296      else { return this.charError(buffer, i); }
297    }else if (this.tState === FALSE3){ // s
298      if (buffer[i] === 0x73) { this.tState = FALSE4; }
299      else { return this.charError(buffer, i); }
300    }else if (this.tState === FALSE4){ // e
301      if (buffer[i] === 0x65) { this.tState = START; this.onToken(FALSE, false); this.offset+= 4; }
302      else { return this.charError(buffer, i); }
303    }else if (this.tState === NULL1){ // u
304      if (buffer[i] === 0x75) { this.tState = NULL2; }
305      else { return this.charError(buffer, i); }
306    }else if (this.tState === NULL2){ // l
307      if (buffer[i] === 0x6c) { this.tState = NULL3; }
308      else { return this.charError(buffer, i); }
309    }else if (this.tState === NULL3){ // l
310      if (buffer[i] === 0x6c) { this.tState = START; this.onToken(NULL, null); this.offset += 3; }
311      else { return this.charError(buffer, i); }
312    }
313  }
314};
315proto.onToken = function (token, value) {
316  // Override this to get events
317};
318
319proto.parseError = function (token, value) {
320  this.tState = STOP;
321  this.onError(new Error("Unexpected " + Parser.toknam(token) + (value ? ("(" + JSON.stringify(value) + ")") : "") + " in state " + Parser.toknam(this.state)));
322};
323proto.push = function () {
324  this.stack.push({value: this.value, key: this.key, mode: this.mode});
325};
326proto.pop = function () {
327  var value = this.value;
328  var parent = this.stack.pop();
329  this.value = parent.value;
330  this.key = parent.key;
331  this.mode = parent.mode;
332  this.emit(value);
333  if (!this.mode) { this.state = VALUE; }
334};
335proto.emit = function (value) {
336  if (this.mode) { this.state = COMMA; }
337  this.onValue(value);
338};
339proto.onValue = function (value) {
340  // Override me
341};
342proto.onToken = function (token, value) {
343  if(this.state === VALUE){
344    if(token === STRING || token === NUMBER || token === TRUE || token === FALSE || token === NULL){
345      if (this.value) {
346        this.value[this.key] = value;
347      }
348      this.emit(value);
349    }else if(token === LEFT_BRACE){
350      this.push();
351      if (this.value) {
352        this.value = this.value[this.key] = {};
353      } else {
354        this.value = {};
355      }
356      this.key = undefined;
357      this.state = KEY;
358      this.mode = OBJECT;
359    }else if(token === LEFT_BRACKET){
360      this.push();
361      if (this.value) {
362        this.value = this.value[this.key] = [];
363      } else {
364        this.value = [];
365      }
366      this.key = 0;
367      this.mode = ARRAY;
368      this.state = VALUE;
369    }else if(token === RIGHT_BRACE){
370      if (this.mode === OBJECT) {
371        this.pop();
372      } else {
373        return this.parseError(token, value);
374      }
375    }else if(token === RIGHT_BRACKET){
376      if (this.mode === ARRAY) {
377        this.pop();
378      } else {
379        return this.parseError(token, value);
380      }
381    }else{
382      return this.parseError(token, value);
383    }
384  }else if(this.state === KEY){
385    if (token === STRING) {
386      this.key = value;
387      this.state = COLON;
388    } else if (token === RIGHT_BRACE) {
389      this.pop();
390    } else {
391      return this.parseError(token, value);
392    }
393  }else if(this.state === COLON){
394    if (token === COLON) { this.state = VALUE; }
395    else { return this.parseError(token, value); }
396  }else if(this.state === COMMA){
397    if (token === COMMA) {
398      if (this.mode === ARRAY) { this.key++; this.state = VALUE; }
399      else if (this.mode === OBJECT) { this.state = KEY; }
400
401    } else if (token === RIGHT_BRACKET && this.mode === ARRAY || token === RIGHT_BRACE && this.mode === OBJECT) {
402      this.pop();
403    } else {
404      return this.parseError(token, value);
405    }
406  }else{
407    return this.parseError(token, value);
408  }
409};
410
411Parser.C = C;
412
413module.exports = Parser;
414