Debian Codegraph @

lib/compiler/passes/generate-js.js

raw symbols SCIP
1 "use strict";
2
3 var arrays = require("../../utils/arrays"),
4 objects = require("../../utils/objects"),
5 asts = require("../asts"),
6 op = require("../opcodes"),
7 js = require("../js");
8
9 /* Generates parser JavaScript code. */
10 function generateJS(ast, options) {
11 /* These only indent non-empty lines to avoid trailing whitespace. */
12 function indent2(code) { return code.replace(/^(.+)$/gm, ' $1'); }
13 function indent6(code) { return code.replace(/^(.+)$/gm, ' $1'); }
14 function indent10(code) { return code.replace(/^(.+)$/gm, ' $1'); }
15
16 function generateTables() {
17 if (options.optimize === "size") {
18 return [
19 'peg$consts = [',
20 indent2(ast.consts.join(',\n')),
21 '],',
22 '',
23 'peg$bytecode = [',
24 indent2(arrays.map(ast.rules, function(rule) {
25 return 'peg$decode("'
26 + js.stringEscape(arrays.map(
27 rule.bytecode,
28 function(b) { return String.fromCharCode(b + 32); }
29 ).join(''))
30 + '")';
31 }).join(',\n')),
32 '],'
33 ].join('\n');
34 } else {
35 return arrays.map(
36 ast.consts,
37 function(c, i) { return 'peg$c' + i + ' = ' + c + ','; }
38 ).join('\n');
39 }
40 }
41
42 function generateRuleHeader(ruleNameCode, ruleIndexCode) {
43 var parts = [];
44
45 parts.push('');
46
47 if (options.trace) {
48 parts.push([
49 'peg$tracer.trace({',
50 ' type: "rule.enter",',
51 ' rule: ' + ruleNameCode + ',',
52 ' location: peg$computeLocation(startPos, startPos)',
53 '});',
54 ''
55 ].join('\n'));
56 }
57
58 if (options.cache) {
59 parts.push([
60 'var key = peg$currPos * ' + ast.rules.length + ' + ' + ruleIndexCode + ',',
61 ' cached = peg$resultsCache[key];',
62 '',
63 'if (cached) {',
64 ' peg$currPos = cached.nextPos;',
65 ''
66 ].join('\n'));
67
68 if (options.trace) {
69 parts.push([
70 'if (cached.result !== peg$FAILED) {',
71 ' peg$tracer.trace({',
72 ' type: "rule.match",',
73 ' rule: ' + ruleNameCode + ',',
74 ' result: cached.result,',
75 ' location: peg$computeLocation(startPos, peg$currPos)',
76 ' });',
77 '} else {',
78 ' peg$tracer.trace({',
79 ' type: "rule.fail",',
80 ' rule: ' + ruleNameCode + ',',
81 ' location: peg$computeLocation(startPos, startPos)',
82 ' });',
83 '}',
84 ''
85 ].join('\n'));
86 }
87
88 parts.push([
89 ' return cached.result;',
90 '}',
91 ''
92 ].join('\n'));
93 }
94
95 return parts.join('\n');
96 }
97
98 function generateRuleFooter(ruleNameCode, resultCode) {
99 var parts = [];
100
101 if (options.cache) {
102 parts.push([
103 '',
104 'peg$resultsCache[key] = { nextPos: peg$currPos, result: ' + resultCode + ' };'
105 ].join('\n'));
106 }
107
108 if (options.trace) {
109 parts.push([
110 '',
111 'if (' + resultCode + ' !== peg$FAILED) {',
112 ' peg$tracer.trace({',
113 ' type: "rule.match",',
114 ' rule: ' + ruleNameCode + ',',
115 ' result: ' + resultCode + ',',
116 ' location: peg$computeLocation(startPos, peg$currPos)',
117 ' });',
118 '} else {',
119 ' peg$tracer.trace({',
120 ' type: "rule.fail",',
121 ' rule: ' + ruleNameCode + ',',
122 ' location: peg$computeLocation(startPos, startPos)',
123 ' });',
124 '}'
125 ].join('\n'));
126 }
127
128 parts.push([
129 '',
130 'return ' + resultCode + ';'
131 ].join('\n'));
132
133 return parts.join('\n');
134 }
135
136 function generateInterpreter() {
137 var parts = [];
138
139 function generateCondition(cond, argsLength) {
140 var baseLength = argsLength + 3,
141 thenLengthCode = 'bc[ip + ' + (baseLength - 2) + ']',
142 elseLengthCode = 'bc[ip + ' + (baseLength - 1) + ']';
143
144 return [
145 'ends.push(end);',
146 'ips.push(ip + ' + baseLength + ' + ' + thenLengthCode + ' + ' + elseLengthCode + ');',
147 '',
148 'if (' + cond + ') {',
149 ' end = ip + ' + baseLength + ' + ' + thenLengthCode + ';',
150 ' ip += ' + baseLength + ';',
151 '} else {',
152 ' end = ip + ' + baseLength + ' + ' + thenLengthCode + ' + ' + elseLengthCode + ';',
153 ' ip += ' + baseLength + ' + ' + thenLengthCode + ';',
154 '}',
155 '',
156 'break;'
157 ].join('\n');
158 }
159
160 function generateLoop(cond) {
161 var baseLength = 2,
162 bodyLengthCode = 'bc[ip + ' + (baseLength - 1) + ']';
163
164 return [
165 'if (' + cond + ') {',
166 ' ends.push(end);',
167 ' ips.push(ip);',
168 '',
169 ' end = ip + ' + baseLength + ' + ' + bodyLengthCode + ';',
170 ' ip += ' + baseLength + ';',
171 '} else {',
172 ' ip += ' + baseLength + ' + ' + bodyLengthCode + ';',
173 '}',
174 '',
175 'break;'
176 ].join('\n');
177 }
178
179 function generateCall() {
180 var baseLength = 4,
181 paramsLengthCode = 'bc[ip + ' + (baseLength - 1) + ']';
182
183 return [
184 'params = bc.slice(ip + ' + baseLength + ', ip + ' + baseLength + ' + ' + paramsLengthCode + ');',
185 'for (i = 0; i < ' + paramsLengthCode + '; i++) {',
186 ' params[i] = stack[stack.length - 1 - params[i]];',
187 '}',
188 '',
189 'stack.splice(',
190 ' stack.length - bc[ip + 2],',
191 ' bc[ip + 2],',
192 ' peg$consts[bc[ip + 1]].apply(null, params)',
193 ');',
194 '',
195 'ip += ' + baseLength + ' + ' + paramsLengthCode + ';',
196 'break;'
197 ].join('\n');
198 }
199
200 parts.push([
201 'function peg$decode(s) {',
202 ' var bc = new Array(s.length), i;',
203 '',
204 ' for (i = 0; i < s.length; i++) {',
205 ' bc[i] = s.charCodeAt(i) - 32;',
206 ' }',
207 '',
208 ' return bc;',
209 '}',
210 '',
211 'function peg$parseRule(index) {'
212 ].join('\n'));
213
214 if (options.trace) {
215 parts.push([
216 ' var bc = peg$bytecode[index],',
217 ' ip = 0,',
218 ' ips = [],',
219 ' end = bc.length,',
220 ' ends = [],',
221 ' stack = [],',
222 ' startPos = peg$currPos,',
223 ' params, i;'
224 ].join('\n'));
225 } else {
226 parts.push([
227 ' var bc = peg$bytecode[index],',
228 ' ip = 0,',
229 ' ips = [],',
230 ' end = bc.length,',
231 ' ends = [],',
232 ' stack = [],',
233 ' params, i;'
234 ].join('\n'));
235 }
236
237 parts.push(indent2(generateRuleHeader('peg$ruleNames[index]', 'index')));
238
239 parts.push([
240 /*
241 * The point of the outer loop and the |ips| & |ends| stacks is to avoid
242 * recursive calls for interpreting parts of bytecode. In other words, we
243 * implement the |interpret| operation of the abstract machine without
244 * function calls. Such calls would likely slow the parser down and more
245 * importantly cause stack overflows for complex grammars.
246 */
247 ' while (true) {',
248 ' while (ip < end) {',
249 ' switch (bc[ip]) {',
250 ' case ' + op.PUSH + ':', // PUSH c
251 ' stack.push(peg$consts[bc[ip + 1]]);',
252 ' ip += 2;',
253 ' break;',
254 '',
255 ' case ' + op.PUSH_UNDEFINED + ':', // PUSH_UNDEFINED
256 ' stack.push(void 0);',
257 ' ip++;',
258 ' break;',
259 '',
260 ' case ' + op.PUSH_NULL + ':', // PUSH_NULL
261 ' stack.push(null);',
262 ' ip++;',
263 ' break;',
264 '',
265 ' case ' + op.PUSH_FAILED + ':', // PUSH_FAILED
266 ' stack.push(peg$FAILED);',
267 ' ip++;',
268 ' break;',
269 '',
270 ' case ' + op.PUSH_EMPTY_ARRAY + ':', // PUSH_EMPTY_ARRAY
271 ' stack.push([]);',
272 ' ip++;',
273 ' break;',
274 '',
275 ' case ' + op.PUSH_CURR_POS + ':', // PUSH_CURR_POS
276 ' stack.push(peg$currPos);',
277 ' ip++;',
278 ' break;',
279 '',
280 ' case ' + op.POP + ':', // POP
281 ' stack.pop();',
282 ' ip++;',
283 ' break;',
284 '',
285 ' case ' + op.POP_CURR_POS + ':', // POP_CURR_POS
286 ' peg$currPos = stack.pop();',
287 ' ip++;',
288 ' break;',
289 '',
290 ' case ' + op.POP_N + ':', // POP_N n
291 ' stack.length -= bc[ip + 1];',
292 ' ip += 2;',
293 ' break;',
294 '',
295 ' case ' + op.NIP + ':', // NIP
296 ' stack.splice(-2, 1);',
297 ' ip++;',
298 ' break;',
299 '',
300 ' case ' + op.APPEND + ':', // APPEND
301 ' stack[stack.length - 2].push(stack.pop());',
302 ' ip++;',
303 ' break;',
304 '',
305 ' case ' + op.WRAP + ':', // WRAP n
306 ' stack.push(stack.splice(stack.length - bc[ip + 1], bc[ip + 1]));',
307 ' ip += 2;',
308 ' break;',
309 '',
310 ' case ' + op.TEXT + ':', // TEXT
311 ' stack.push(input.substring(stack.pop(), peg$currPos));',
312 ' ip++;',
313 ' break;',
314 '',
315 ' case ' + op.IF + ':', // IF t, f
316 indent10(generateCondition('stack[stack.length - 1]', 0)),
317 '',
318 ' case ' + op.IF_ERROR + ':', // IF_ERROR t, f
319 indent10(generateCondition(
320 'stack[stack.length - 1] === peg$FAILED',
321 0
322 )),
323 '',
324 ' case ' + op.IF_NOT_ERROR + ':', // IF_NOT_ERROR t, f
325 indent10(
326 generateCondition('stack[stack.length - 1] !== peg$FAILED',
327 0
328 )),
329 '',
330 ' case ' + op.WHILE_NOT_ERROR + ':', // WHILE_NOT_ERROR b
331 indent10(generateLoop('stack[stack.length - 1] !== peg$FAILED')),
332 '',
333 ' case ' + op.MATCH_ANY + ':', // MATCH_ANY a, f, ...
334 indent10(generateCondition('input.length > peg$currPos', 0)),
335 '',
336 ' case ' + op.MATCH_STRING + ':', // MATCH_STRING s, a, f, ...
337 indent10(generateCondition(
338 'input.substr(peg$currPos, peg$consts[bc[ip + 1]].length) === peg$consts[bc[ip + 1]]',
339 1
340 )),
341 '',
342 ' case ' + op.MATCH_STRING_IC + ':', // MATCH_STRING_IC s, a, f, ...
343 indent10(generateCondition(
344 'input.substr(peg$currPos, peg$consts[bc[ip + 1]].length).toLowerCase() === peg$consts[bc[ip + 1]]',
345 1
346 )),
347 '',
348 ' case ' + op.MATCH_REGEXP + ':', // MATCH_REGEXP r, a, f, ...
349 indent10(generateCondition(
350 'peg$consts[bc[ip + 1]].test(input.charAt(peg$currPos))',
351 1
352 )),
353 '',
354 ' case ' + op.ACCEPT_N + ':', // ACCEPT_N n
355 ' stack.push(input.substr(peg$currPos, bc[ip + 1]));',
356 ' peg$currPos += bc[ip + 1];',
357 ' ip += 2;',
358 ' break;',
359 '',
360 ' case ' + op.ACCEPT_STRING + ':', // ACCEPT_STRING s
361 ' stack.push(peg$consts[bc[ip + 1]]);',
362 ' peg$currPos += peg$consts[bc[ip + 1]].length;',
363 ' ip += 2;',
364 ' break;',
365 '',
366 ' case ' + op.FAIL + ':', // FAIL e
367 ' stack.push(peg$FAILED);',
368 ' if (peg$silentFails === 0) {',
369 ' peg$fail(peg$consts[bc[ip + 1]]);',
370 ' }',
371 ' ip += 2;',
372 ' break;',
373 '',
374 ' case ' + op.LOAD_SAVED_POS + ':', // LOAD_SAVED_POS p
375 ' peg$savedPos = stack[stack.length - 1 - bc[ip + 1]];',
376 ' ip += 2;',
377 ' break;',
378 '',
379 ' case ' + op.UPDATE_SAVED_POS + ':', // UPDATE_SAVED_POS
380 ' peg$savedPos = peg$currPos;',
381 ' ip++;',
382 ' break;',
383 '',
384 ' case ' + op.CALL + ':', // CALL f, n, pc, p1, p2, ..., pN
385 indent10(generateCall()),
386 '',
387 ' case ' + op.RULE + ':', // RULE r
388 ' stack.push(peg$parseRule(bc[ip + 1]));',
389 ' ip += 2;',
390 ' break;',
391 '',
392 ' case ' + op.SILENT_FAILS_ON + ':', // SILENT_FAILS_ON
393 ' peg$silentFails++;',
394 ' ip++;',
395 ' break;',
396 '',
397 ' case ' + op.SILENT_FAILS_OFF + ':', // SILENT_FAILS_OFF
398 ' peg$silentFails--;',
399 ' ip++;',
400 ' break;',
401 '',
402 ' default:',
403 ' throw new Error("Invalid opcode: " + bc[ip] + ".");',
404 ' }',
405 ' }',
406 '',
407 ' if (ends.length > 0) {',
408 ' end = ends.pop();',
409 ' ip = ips.pop();',
410 ' } else {',
411 ' break;',
412 ' }',
413 ' }'
414 ].join('\n'));
415
416 parts.push(indent2(generateRuleFooter('peg$ruleNames[index]', 'stack[0]')));
417 parts.push('}');
418
419 return parts.join('\n');
420 }
421
422 function generateRuleFunction(rule) {
423 var parts = [], code;
424
425 function c(i) { return "peg$c" + i; } // |consts[i]| of the abstract machine
426 function s(i) { return "s" + i; } // |stack[i]| of the abstract machine
427
428 var stack = {
429 sp: -1,
430 maxSp: -1,
431
432 push: function(exprCode) {
433 var code = s(++this.sp) + ' = ' + exprCode + ';';
434
435 if (this.sp > this.maxSp) { this.maxSp = this.sp; }
436
437 return code;
438 },
439
440 pop: function(n) {
441 var values;
442
443 if (n === void 0) {
444 return s(this.sp--);
445 } else {
446 values = arrays.map(arrays.range(this.sp - n + 1, this.sp + 1), s);
447 this.sp -= n;
448
449 return values;
450 }
451 },
452
453 top: function() {
454 return s(this.sp);
455 },
456
457 index: function(i) {
458 return s(this.sp - i);
459 }
460 };
461
462 function compile(bc) {
463 var ip = 0,
464 end = bc.length,
465 parts = [],
466 value;
467
468 function compileCondition(cond, argCount) {
469 var baseLength = argCount + 3,
470 thenLength = bc[ip + baseLength - 2],
471 elseLength = bc[ip + baseLength - 1],
472 baseSp = stack.sp,
473 thenCode, elseCode, thenSp, elseSp;
474
475 ip += baseLength;
476 thenCode = compile(bc.slice(ip, ip + thenLength));
477 thenSp = stack.sp;
478 ip += thenLength;
479
480 if (elseLength > 0) {
481 stack.sp = baseSp;
482 elseCode = compile(bc.slice(ip, ip + elseLength));
483 elseSp = stack.sp;
484 ip += elseLength;
485
486 if (thenSp !== elseSp) {
487 throw new Error(
488 "Branches of a condition must move the stack pointer in the same way."
489 );
490 }
491 }
492
493 parts.push('if (' + cond + ') {');
494 parts.push(indent2(thenCode));
495 if (elseLength > 0) {
496 parts.push('} else {');
497 parts.push(indent2(elseCode));
498 }
499 parts.push('}');
500 }
501
502 function compileLoop(cond) {
503 var baseLength = 2,
504 bodyLength = bc[ip + baseLength - 1],
505 baseSp = stack.sp,
506 bodyCode, bodySp;
507
508 ip += baseLength;
509 bodyCode = compile(bc.slice(ip, ip + bodyLength));
510 bodySp = stack.sp;
511 ip += bodyLength;
512
513 if (bodySp !== baseSp) {
514 throw new Error("Body of a loop can't move the stack pointer.");
515 }
516
517 parts.push('while (' + cond + ') {');
518 parts.push(indent2(bodyCode));
519 parts.push('}');
520 }
521
522 function compileCall() {
523 var baseLength = 4,
524 paramsLength = bc[ip + baseLength - 1];
525
526 var value = c(bc[ip + 1]) + '('
527 + arrays.map(
528 bc.slice(ip + baseLength, ip + baseLength + paramsLength),
529 function(p) { return stack.index(p); }
530 ).join(', ')
531 + ')';
532 stack.pop(bc[ip + 2]);
533 parts.push(stack.push(value));
534 ip += baseLength + paramsLength;
535 }
536
537 while (ip < end) {
538 switch (bc[ip]) {
539 case op.PUSH: // PUSH c
540 parts.push(stack.push(c(bc[ip + 1])));
541 ip += 2;
542 break;
543
544 case op.PUSH_CURR_POS: // PUSH_CURR_POS
545 parts.push(stack.push('peg$currPos'));
546 ip++;
547 break;
548
549 case op.PUSH_UNDEFINED: // PUSH_UNDEFINED
550 parts.push(stack.push('void 0'));
551 ip++;
552 break;
553
554 case op.PUSH_NULL: // PUSH_NULL
555 parts.push(stack.push('null'));
556 ip++;
557 break;
558
559 case op.PUSH_FAILED: // PUSH_FAILED
560 parts.push(stack.push('peg$FAILED'));
561 ip++;
562 break;
563
564 case op.PUSH_EMPTY_ARRAY: // PUSH_EMPTY_ARRAY
565 parts.push(stack.push('[]'));
566 ip++;
567 break;
568
569 case op.POP: // POP
570 stack.pop();
571 ip++;
572 break;
573
574 case op.POP_CURR_POS: // POP_CURR_POS
575 parts.push('peg$currPos = ' + stack.pop() + ';');
576 ip++;
577 break;
578
579 case op.POP_N: // POP_N n
580 stack.pop(bc[ip + 1]);
581 ip += 2;
582 break;
583
584 case op.NIP: // NIP
585 value = stack.pop();
586 stack.pop();
587 parts.push(stack.push(value));
588 ip++;
589 break;
590
591 case op.APPEND: // APPEND
592 value = stack.pop();
593 parts.push(stack.top() + '.push(' + value + ');');
594 ip++;
595 break;
596
597 case op.WRAP: // WRAP n
598 parts.push(
599 stack.push('[' + stack.pop(bc[ip + 1]).join(', ') + ']')
600 );
601 ip += 2;
602 break;
603
604 case op.TEXT: // TEXT
605 parts.push(
606 stack.push('input.substring(' + stack.pop() + ', peg$currPos)')
607 );
608 ip++;
609 break;
610
611 case op.IF: // IF t, f
612 compileCondition(stack.top(), 0);
613 break;
614
615 case op.IF_ERROR: // IF_ERROR t, f
616 compileCondition(stack.top() + ' === peg$FAILED', 0);
617 break;
618
619 case op.IF_NOT_ERROR: // IF_NOT_ERROR t, f
620 compileCondition(stack.top() + ' !== peg$FAILED', 0);
621 break;
622
623 case op.WHILE_NOT_ERROR: // WHILE_NOT_ERROR b
624 compileLoop(stack.top() + ' !== peg$FAILED', 0);
625 break;
626
627 case op.MATCH_ANY: // MATCH_ANY a, f, ...
628 compileCondition('input.length > peg$currPos', 0);
629 break;
630
631 case op.MATCH_STRING: // MATCH_STRING s, a, f, ...
632 compileCondition(
633 eval(ast.consts[bc[ip + 1]]).length > 1
634 ? 'input.substr(peg$currPos, '
635 + eval(ast.consts[bc[ip + 1]]).length
636 + ') === '
637 + c(bc[ip + 1])
638 : 'input.charCodeAt(peg$currPos) === '
639 + eval(ast.consts[bc[ip + 1]]).charCodeAt(0),
640 1
641 );
642 break;
643
644 case op.MATCH_STRING_IC: // MATCH_STRING_IC s, a, f, ...
645 compileCondition(
646 'input.substr(peg$currPos, '
647 + eval(ast.consts[bc[ip + 1]]).length
648 + ').toLowerCase() === '
649 + c(bc[ip + 1]),
650 1
651 );
652 break;
653
654 case op.MATCH_REGEXP: // MATCH_REGEXP r, a, f, ...
655 compileCondition(
656 c(bc[ip + 1]) + '.test(input.charAt(peg$currPos))',
657 1
658 );
659 break;
660
661 case op.ACCEPT_N: // ACCEPT_N n
662 parts.push(stack.push(
663 bc[ip + 1] > 1
664 ? 'input.substr(peg$currPos, ' + bc[ip + 1] + ')'
665 : 'input.charAt(peg$currPos)'
666 ));
667 parts.push(
668 bc[ip + 1] > 1
669 ? 'peg$currPos += ' + bc[ip + 1] + ';'
670 : 'peg$currPos++;'
671 );
672 ip += 2;
673 break;
674
675 case op.ACCEPT_STRING: // ACCEPT_STRING s
676 parts.push(stack.push(c(bc[ip + 1])));
677 parts.push(
678 eval(ast.consts[bc[ip + 1]]).length > 1
679 ? 'peg$currPos += ' + eval(ast.consts[bc[ip + 1]]).length + ';'
680 : 'peg$currPos++;'
681 );
682 ip += 2;
683 break;
684
685 case op.FAIL: // FAIL e
686 parts.push(stack.push('peg$FAILED'));
687 parts.push('if (peg$silentFails === 0) { peg$fail(' + c(bc[ip + 1]) + '); }');
688 ip += 2;
689 break;
690
691 case op.LOAD_SAVED_POS: // LOAD_SAVED_POS p
692 parts.push('peg$savedPos = ' + stack.index(bc[ip + 1]) + ';');
693 ip += 2;
694 break;
695
696 case op.UPDATE_SAVED_POS: // UPDATE_SAVED_POS
697 parts.push('peg$savedPos = peg$currPos;');
698 ip++;
699 break;
700
701 case op.CALL: // CALL f, n, pc, p1, p2, ..., pN
702 compileCall();
703 break;
704
705 case op.RULE: // RULE r
706 parts.push(stack.push("peg$parse" + ast.rules[bc[ip + 1]].name + "()"));
707 ip += 2;
708 break;
709
710 case op.SILENT_FAILS_ON: // SILENT_FAILS_ON
711 parts.push('peg$silentFails++;');
712 ip++;
713 break;
714
715 case op.SILENT_FAILS_OFF: // SILENT_FAILS_OFF
716 parts.push('peg$silentFails--;');
717 ip++;
718 break;
719
720 default:
721 throw new Error("Invalid opcode: " + bc[ip] + ".");
722 }
723 }
724
725 return parts.join('\n');
726 }
727
728 code = compile(rule.bytecode);
729
730 parts.push('function peg$parse' + rule.name + '() {');
731
732 if (options.trace) {
733 parts.push([
734 ' var ' + arrays.map(arrays.range(0, stack.maxSp + 1), s).join(', ') + ',',
735 ' startPos = peg$currPos;'
736 ].join('\n'));
737 } else {
738 parts.push(
739 ' var ' + arrays.map(arrays.range(0, stack.maxSp + 1), s).join(', ') + ';'
740 );
741 }
742
743 parts.push(indent2(generateRuleHeader(
744 '"' + js.stringEscape(rule.name) + '"',
745 asts.indexOfRule(ast, rule.name)
746 )));
747 parts.push(indent2(code));
748 parts.push(indent2(generateRuleFooter(
749 '"' + js.stringEscape(rule.name) + '"',
750 s(0)
751 )));
752
753 parts.push('}');
754
755 return parts.join('\n');
756 }
757
758 function generateToplevel() {
759 var parts = [],
760 startRuleIndices, startRuleIndex,
761 startRuleFunctions, startRuleFunction,
762 ruleNames;
763
764 parts.push([
765 'function peg$subclass(child, parent) {',
766 ' function ctor() { this.constructor = child; }',
767 ' ctor.prototype = parent.prototype;',
768 ' child.prototype = new ctor();',
769 '}',
770 '',
771 'function peg$SyntaxError(message, expected, found, location) {',
772 ' this.message = message;',
773 ' this.expected = expected;',
774 ' this.found = found;',
775 ' this.location = location;',
776 ' this.name = "SyntaxError";',
777 '',
778 ' if (typeof Error.captureStackTrace === "function") {',
779 ' Error.captureStackTrace(this, peg$SyntaxError);',
780 ' }',
781 '}',
782 '',
783 'peg$subclass(peg$SyntaxError, Error);',
784 '',
785 'peg$SyntaxError.buildMessage = function(expected, found) {',
786 ' var DESCRIBE_EXPECTATION_FNS = {',
787 ' literal: function(expectation) {',
788 ' return "\\\"" + literalEscape(expectation.text) + "\\\"";',
789 ' },',
790 '',
791 ' "class": function(expectation) {',
792 ' var escapedParts = "",',
793 ' i;',
794 '',
795 ' for (i = 0; i < expectation.parts.length; i++) {',
796 ' escapedParts += expectation.parts[i] instanceof Array',
797 ' ? classEscape(expectation.parts[i][0]) + "-" + classEscape(expectation.parts[i][1])',
798 ' : classEscape(expectation.parts[i]);',
799 ' }',
800 '',
801 ' return "[" + (expectation.inverted ? "^" : "") + escapedParts + "]";',
802 ' },',
803 '',
804 ' any: function(expectation) {',
805 ' return "any character";',
806 ' },',
807 '',
808 ' end: function(expectation) {',
809 ' return "end of input";',
810 ' },',
811 '',
812 ' other: function(expectation) {',
813 ' return expectation.description;',
814 ' }',
815 ' };',
816 '',
817 ' function hex(ch) {',
818 ' return ch.charCodeAt(0).toString(16).toUpperCase();',
819 ' }',
820 '',
821 ' function literalEscape(s) {',
822 ' return s',
823 ' .replace(/\\\\/g, \'\\\\\\\\\')', // backslash
824 ' .replace(/"/g, \'\\\\"\')', // closing double quote
825 ' .replace(/\\0/g, \'\\\\0\')', // null
826 ' .replace(/\\t/g, \'\\\\t\')', // horizontal tab
827 ' .replace(/\\n/g, \'\\\\n\')', // line feed
828 ' .replace(/\\r/g, \'\\\\r\')', // carriage return
829 ' .replace(/[\\x00-\\x0F]/g, function(ch) { return \'\\\\x0\' + hex(ch); })',
830 ' .replace(/[\\x10-\\x1F\\x7F-\\x9F]/g, function(ch) { return \'\\\\x\' + hex(ch); });',
831 ' }',
832 '',
833 ' function classEscape(s) {',
834 ' return s',
835 ' .replace(/\\\\/g, \'\\\\\\\\\')', // backslash
836 ' .replace(/\\]/g, \'\\\\]\')', // closing bracket
837 ' .replace(/\\^/g, \'\\\\^\')', // caret
838 ' .replace(/-/g, \'\\\\-\')', // dash
839 ' .replace(/\\0/g, \'\\\\0\')', // null
840 ' .replace(/\\t/g, \'\\\\t\')', // horizontal tab
841 ' .replace(/\\n/g, \'\\\\n\')', // line feed
842 ' .replace(/\\r/g, \'\\\\r\')', // carriage return
843 ' .replace(/[\\x00-\\x0F]/g, function(ch) { return \'\\\\x0\' + hex(ch); })',
844 ' .replace(/[\\x10-\\x1F\\x7F-\\x9F]/g, function(ch) { return \'\\\\x\' + hex(ch); });',
845 ' }',
846 '',
847 ' function describeExpectation(expectation) {',
848 ' return DESCRIBE_EXPECTATION_FNS[expectation.type](expectation);',
849 ' }',
850 '',
851 ' function describeExpected(expected) {',
852 ' var descriptions = new Array(expected.length),',
853 ' i, j;',
854 '',
855 ' for (i = 0; i < expected.length; i++) {',
856 ' descriptions[i] = describeExpectation(expected[i]);',
857 ' }',
858 '',
859 ' descriptions.sort();',
860 '',
861 ' if (descriptions.length > 0) {',
862 ' for (i = 1, j = 1; i < descriptions.length; i++) {',
863 ' if (descriptions[i - 1] !== descriptions[i]) {',
864 ' descriptions[j] = descriptions[i];',
865 ' j++;',
866 ' }',
867 ' }',
868 ' descriptions.length = j;',
869 ' }',
870 '',
871 ' switch (descriptions.length) {',
872 ' case 1:',
873 ' return descriptions[0];',
874 '',
875 ' case 2:',
876 ' return descriptions[0] + " or " + descriptions[1];',
877 '',
878 ' default:',
879 ' return descriptions.slice(0, -1).join(", ")',
880 ' + ", or "',
881 ' + descriptions[descriptions.length - 1];',
882 ' }',
883 ' }',
884 '',
885 ' function describeFound(found) {',
886 ' return found ? "\\"" + literalEscape(found) + "\\"" : "end of input";',
887 ' }',
888 '',
889 ' return "Expected " + describeExpected(expected) + " but " + describeFound(found) + " found.";',
890 '};',
891 ''
892 ].join('\n'));
893
894 if (options.trace) {
895 parts.push([
896 'function peg$DefaultTracer() {',
897 ' this.indentLevel = 0;',
898 '}',
899 '',
900 'peg$DefaultTracer.prototype.trace = function(event) {',
901 ' var that = this;',
902 '',
903 ' function log(event) {',
904 ' function repeat(string, n) {',
905 ' var result = "", i;',
906 '',
907 ' for (i = 0; i < n; i++) {',
908 ' result += string;',
909 ' }',
910 '',
911 ' return result;',
912 ' }',
913 '',
914 ' function pad(string, length) {',
915 ' return string + repeat(" ", length - string.length);',
916 ' }',
917 '',
918 ' if (typeof console === "object") {', // IE 8-10
919 ' console.log(',
920 ' event.location.start.line + ":" + event.location.start.column + "-"',
921 ' + event.location.end.line + ":" + event.location.end.column + " "',
922 ' + pad(event.type, 10) + " "',
923 ' + repeat(" ", that.indentLevel) + event.rule',
924 ' );',
925 ' }',
926 ' }',
927 '',
928 ' switch (event.type) {',
929 ' case "rule.enter":',
930 ' log(event);',
931 ' this.indentLevel++;',
932 ' break;',
933 '',
934 ' case "rule.match":',
935 ' this.indentLevel--;',
936 ' log(event);',
937 ' break;',
938 '',
939 ' case "rule.fail":',
940 ' this.indentLevel--;',
941 ' log(event);',
942 ' break;',
943 '',
944 ' default:',
945 ' throw new Error("Invalid event type: " + event.type + ".");',
946 ' }',
947 '};',
948 ''
949 ].join('\n'));
950 }
951
952 parts.push([
953 'function peg$parse(input, options) {',
954 ' options = options !== void 0 ? options : {};',
955 '',
956 ' var peg$FAILED = {},',
957 ''
958 ].join('\n'));
959
960 if (options.optimize === "size") {
961 startRuleIndices = '{ '
962 + arrays.map(
963 options.allowedStartRules,
964 function(r) { return r + ': ' + asts.indexOfRule(ast, r); }
965 ).join(', ')
966 + ' }';
967 startRuleIndex = asts.indexOfRule(ast, options.allowedStartRules[0]);
968
969 parts.push([
970 ' peg$startRuleIndices = ' + startRuleIndices + ',',
971 ' peg$startRuleIndex = ' + startRuleIndex + ','
972 ].join('\n'));
973 } else {
974 startRuleFunctions = '{ '
975 + arrays.map(
976 options.allowedStartRules,
977 function(r) { return r + ': peg$parse' + r; }
978 ).join(', ')
979 + ' }';
980 startRuleFunction = 'peg$parse' + options.allowedStartRules[0];
981
982 parts.push([
983 ' peg$startRuleFunctions = ' + startRuleFunctions + ',',
984 ' peg$startRuleFunction = ' + startRuleFunction + ','
985 ].join('\n'));
986 }
987
988 parts.push('');
989
990 parts.push(indent6(generateTables()));
991
992 parts.push([
993 '',
994 ' peg$currPos = 0,',
995 ' peg$savedPos = 0,',
996 ' peg$posDetailsCache = [{ line: 1, column: 1 }],',
997 ' peg$maxFailPos = 0,',
998 ' peg$maxFailExpected = [],',
999 ' peg$silentFails = 0,', // 0 = report failures, > 0 = silence failures
1000 ''
1001 ].join('\n'));
1002
1003 if (options.cache) {
1004 parts.push([
1005 ' peg$resultsCache = {},',
1006 ''
1007 ].join('\n'));
1008 }
1009
1010 if (options.trace) {
1011 if (options.optimize === "size") {
1012 ruleNames = '['
1013 + arrays.map(
1014 ast.rules,
1015 function(r) { return '"' + js.stringEscape(r.name) + '"'; }
1016 ).join(', ')
1017 + ']';
1018
1019 parts.push([
1020 ' peg$ruleNames = ' + ruleNames + ',',
1021 ''
1022 ].join('\n'));
1023 }
1024
1025 parts.push([
1026 ' peg$tracer = "tracer" in options ? options.tracer : new peg$DefaultTracer(),',
1027 ''
1028 ].join('\n'));
1029 }
1030
1031 parts.push([
1032 ' peg$result;',
1033 ''
1034 ].join('\n'));
1035
1036 if (options.optimize === "size") {
1037 parts.push([
1038 ' if ("startRule" in options) {',
1039 ' if (!(options.startRule in peg$startRuleIndices)) {',
1040 ' throw new Error("Can\'t start parsing from rule \\"" + options.startRule + "\\".");',
1041 ' }',
1042 '',
1043 ' peg$startRuleIndex = peg$startRuleIndices[options.startRule];',
1044 ' }'
1045 ].join('\n'));
1046 } else {
1047 parts.push([
1048 ' if ("startRule" in options) {',
1049 ' if (!(options.startRule in peg$startRuleFunctions)) {',
1050 ' throw new Error("Can\'t start parsing from rule \\"" + options.startRule + "\\".");',
1051 ' }',
1052 '',
1053 ' peg$startRuleFunction = peg$startRuleFunctions[options.startRule];',
1054 ' }'
1055 ].join('\n'));
1056 }
1057
1058 parts.push([
1059 '',
1060 ' function text() {',
1061 ' return input.substring(peg$savedPos, peg$currPos);',
1062 ' }',
1063 '',
1064 ' function location() {',
1065 ' return peg$computeLocation(peg$savedPos, peg$currPos);',
1066 ' }',
1067 '',
1068 ' function expected(description, location) {',
1069 ' location = location !== void 0 ? location : peg$computeLocation(peg$savedPos, peg$currPos)',
1070 '',
1071 ' throw peg$buildStructuredError(',
1072 ' [peg$otherExpectation(description)],',
1073 ' input.substring(peg$savedPos, peg$currPos),',
1074 ' location',
1075 ' );',
1076 ' }',
1077 '',
1078 ' function error(message, location) {',
1079 ' location = location !== void 0 ? location : peg$computeLocation(peg$savedPos, peg$currPos)',
1080 '',
1081 ' throw peg$buildSimpleError(message, location);',
1082 ' }',
1083 '',
1084 ' function peg$literalExpectation(text, ignoreCase) {',
1085 ' return { type: "literal", text: text, ignoreCase: ignoreCase };',
1086 ' }',
1087 '',
1088 ' function peg$classExpectation(parts, inverted, ignoreCase) {',
1089 ' return { type: "class", parts: parts, inverted: inverted, ignoreCase: ignoreCase };',
1090 ' }',
1091 '',
1092 ' function peg$anyExpectation() {',
1093 ' return { type: "any" };',
1094 ' }',
1095 '',
1096 ' function peg$endExpectation() {',
1097 ' return { type: "end" };',
1098 ' }',
1099 '',
1100 ' function peg$otherExpectation(description) {',
1101 ' return { type: "other", description: description };',
1102 ' }',
1103 '',
1104 ' function peg$computePosDetails(pos) {',
1105 ' var details = peg$posDetailsCache[pos], p;',
1106 '',
1107 ' if (details) {',
1108 ' return details;',
1109 ' } else {',
1110 ' p = pos - 1;',
1111 ' while (!peg$posDetailsCache[p]) {',
1112 ' p--;',
1113 ' }',
1114 '',
1115 ' details = peg$posDetailsCache[p];',
1116 ' details = {',
1117 ' line: details.line,',
1118 ' column: details.column',
1119 ' };',
1120 '',
1121 ' while (p < pos) {',
1122 ' if (input.charCodeAt(p) === 10) {',
1123 ' details.line++;',
1124 ' details.column = 1;',
1125 ' } else {',
1126 ' details.column++;',
1127 ' }',
1128 '',
1129 ' p++;',
1130 ' }',
1131 '',
1132 ' peg$posDetailsCache[pos] = details;',
1133 ' return details;',
1134 ' }',
1135 ' }',
1136 '',
1137 ' function peg$computeLocation(startPos, endPos) {',
1138 ' var startPosDetails = peg$computePosDetails(startPos),',
1139 ' endPosDetails = peg$computePosDetails(endPos);',
1140 '',
1141 ' return {',
1142 ' start: {',
1143 ' offset: startPos,',
1144 ' line: startPosDetails.line,',
1145 ' column: startPosDetails.column',
1146 ' },',
1147 ' end: {',
1148 ' offset: endPos,',
1149 ' line: endPosDetails.line,',
1150 ' column: endPosDetails.column',
1151 ' }',
1152 ' };',
1153 ' }',
1154 '',
1155 ' function peg$fail(expected) {',
1156 ' if (peg$currPos < peg$maxFailPos) { return; }',
1157 '',
1158 ' if (peg$currPos > peg$maxFailPos) {',
1159 ' peg$maxFailPos = peg$currPos;',
1160 ' peg$maxFailExpected = [];',
1161 ' }',
1162 '',
1163 ' peg$maxFailExpected.push(expected);',
1164 ' }',
1165 '',
1166 ' function peg$buildSimpleError(message, location) {',
1167 ' return new peg$SyntaxError(message, null, null, location);',
1168 ' }',
1169 '',
1170 ' function peg$buildStructuredError(expected, found, location) {',
1171 ' return new peg$SyntaxError(',
1172 ' peg$SyntaxError.buildMessage(expected, found),',
1173 ' expected,',
1174 ' found,',
1175 ' location',
1176 ' );',
1177 ' }',
1178 ''
1179 ].join('\n'));
1180
1181 if (options.optimize === "size") {
1182 parts.push(indent2(generateInterpreter()));
1183 parts.push('');
1184 } else {
1185 arrays.each(ast.rules, function(rule) {
1186 parts.push(indent2(generateRuleFunction(rule)));
1187 parts.push('');
1188 });
1189 }
1190
1191 if (ast.initializer) {
1192 parts.push(indent2(ast.initializer.code));
1193 parts.push('');
1194 }
1195
1196 if (options.optimize === "size") {
1197 parts.push(' peg$result = peg$parseRule(peg$startRuleIndex);');
1198 } else {
1199 parts.push(' peg$result = peg$startRuleFunction();');
1200 }
1201
1202 parts.push([
1203 '',
1204 ' if (peg$result !== peg$FAILED && peg$currPos === input.length) {',
1205 ' return peg$result;',
1206 ' } else {',
1207 ' if (peg$result !== peg$FAILED && peg$currPos < input.length) {',
1208 ' peg$fail(peg$endExpectation());',
1209 ' }',
1210 '',
1211 ' throw peg$buildStructuredError(',
1212 ' peg$maxFailExpected,',
1213 ' peg$maxFailPos < input.length ? input.charAt(peg$maxFailPos) : null,',
1214 ' peg$maxFailPos < input.length',
1215 ' ? peg$computeLocation(peg$maxFailPos, peg$maxFailPos + 1)',
1216 ' : peg$computeLocation(peg$maxFailPos, peg$maxFailPos)',
1217 ' );',
1218 ' }',
1219 '}'
1220 ].join('\n'));
1221
1222 return parts.join('\n');
1223 }
1224
1225 function generateWrapper(toplevelCode) {
1226 function generateGeneratedByComment() {
1227 return [
1228 '/*',
1229 ' * Generated by PEG.js 0.10.0.',
1230 ' *',
1231 ' * http://pegjs.org/',
1232 ' */'
1233 ].join('\n');
1234 }
1235
1236 function generateParserObject() {
1237 return options.trace
1238 ? [
1239 '{',
1240 ' SyntaxError: peg$SyntaxError,',
1241 ' DefaultTracer: peg$DefaultTracer,',
1242 ' parse: peg$parse',
1243 '}'
1244 ].join('\n')
1245 : [
1246 '{',
1247 ' SyntaxError: peg$SyntaxError,',
1248 ' parse: peg$parse',
1249 '}'
1250 ].join('\n');
1251 }
1252
1253 var generators = {
1254 bare: function() {
1255 return [
1256 generateGeneratedByComment(),
1257 '(function() {',
1258 ' "use strict";',
1259 '',
1260 indent2(toplevelCode),
1261 '',
1262 indent2('return ' + generateParserObject() + ';'),
1263 '})()'
1264 ].join('\n');
1265 },
1266
1267 commonjs: function() {
1268 var parts = [],
1269 dependencyVars = objects.keys(options.dependencies),
1270 requires = arrays.map(
1271 dependencyVars,
1272 function(variable) {
1273 return variable
1274 + ' = require("'
1275 + js.stringEscape(options.dependencies[variable])
1276 + '")';
1277 }
1278 );
1279
1280 parts.push([
1281 generateGeneratedByComment(),
1282 '',
1283 '"use strict";',
1284 ''
1285 ].join('\n'));
1286
1287 if (requires.length > 0) {
1288 parts.push('var ' + requires.join(', ') + ';');
1289 parts.push('');
1290 }
1291
1292 parts.push([
1293 toplevelCode,
1294 '',
1295 'module.exports = ' + generateParserObject() + ';',
1296 ''
1297 ].join('\n'));
1298
1299 return parts.join('\n');
1300 },
1301
1302 amd: function() {
1303 var dependencyIds = objects.values(options.dependencies),
1304 dependencyVars = objects.keys(options.dependencies),
1305 dependencies = '['
1306 + arrays.map(
1307 dependencyIds,
1308 function(id) { return '"' + js.stringEscape(id) + '"'; }
1309 ).join(', ')
1310 + ']',
1311 params = dependencyVars.join(', ');
1312
1313 return [
1314 generateGeneratedByComment(),
1315 'define(' + dependencies + ', function(' + params + ') {',
1316 ' "use strict";',
1317 '',
1318 indent2(toplevelCode),
1319 '',
1320 indent2('return ' + generateParserObject() + ';'),
1321 '});',
1322 ''
1323 ].join('\n');
1324 },
1325
1326 globals: function() {
1327 return [
1328 generateGeneratedByComment(),
1329 '(function(root) {',
1330 ' "use strict";',
1331 '',
1332 indent2(toplevelCode),
1333 '',
1334 indent2('root.' + options.exportVar + ' = ' + generateParserObject() + ';'),
1335 '})(this);',
1336 ''
1337 ].join('\n');
1338 },
1339
1340 umd: function() {
1341 var parts = [],
1342 dependencyIds = objects.values(options.dependencies),
1343 dependencyVars = objects.keys(options.dependencies),
1344 dependencies = '['
1345 + arrays.map(
1346 dependencyIds,
1347 function(id) { return '"' + js.stringEscape(id) + '"'; }
1348 ).join(', ')
1349 + ']',
1350 requires = arrays.map(
1351 dependencyIds,
1352 function(id) { return 'require("' + js.stringEscape(id) + '")'; }
1353 ).join(', '),
1354 params = dependencyVars.join(', ');
1355
1356 parts.push([
1357 generateGeneratedByComment(),
1358 '(function(root, factory) {',
1359 ' if (typeof define === "function" && define.amd) {',
1360 ' define(' + dependencies + ', factory);',
1361 ' } else if (typeof module === "object" && module.exports) {',
1362 ' module.exports = factory(' + requires + ');'
1363 ].join('\n'));
1364
1365 if (options.exportVar !== null) {
1366 parts.push([
1367 ' } else {',
1368 ' root.' + options.exportVar + ' = factory();'
1369 ].join('\n'));
1370 }
1371
1372 parts.push([
1373 ' }',
1374 '})(this, function(' + params + ') {',
1375 ' "use strict";',
1376 '',
1377 indent2(toplevelCode),
1378 '',
1379 indent2('return ' + generateParserObject() + ';'),
1380 '});',
1381 ''
1382 ].join('\n'));
1383
1384 return parts.join('\n');
1385 }
1386 };
1387
1388 return generators[options.format]();
1389 }
1390
1391 ast.code = generateWrapper(generateToplevel());
1392 }
1393
1394 module.exports = generateJS;