Debian Codegraph @

lib/compiler/passes/generate-bytecode.js

raw symbols SCIP
1 "use strict";
2
3 var arrays = require("../../utils/arrays"),
4 objects = require("../../utils/objects"),
5 asts = require("../asts"),
6 visitor = require("../visitor"),
7 op = require("../opcodes"),
8 js = require("../js");
9
10 /* Generates bytecode.
11 *
12 * Instructions
13 * ============
14 *
15 * Stack Manipulation
16 * ------------------
17 *
18 * [0] PUSH c
19 *
20 * stack.push(consts[c]);
21 *
22 * [1] PUSH_UNDEFINED
23 *
24 * stack.push(undefined);
25 *
26 * [2] PUSH_NULL
27 *
28 * stack.push(null);
29 *
30 * [3] PUSH_FAILED
31 *
32 * stack.push(FAILED);
33 *
34 * [4] PUSH_EMPTY_ARRAY
35 *
36 * stack.push([]);
37 *
38 * [5] PUSH_CURR_POS
39 *
40 * stack.push(currPos);
41 *
42 * [6] POP
43 *
44 * stack.pop();
45 *
46 * [7] POP_CURR_POS
47 *
48 * currPos = stack.pop();
49 *
50 * [8] POP_N n
51 *
52 * stack.pop(n);
53 *
54 * [9] NIP
55 *
56 * value = stack.pop();
57 * stack.pop();
58 * stack.push(value);
59 *
60 * [10] APPEND
61 *
62 * value = stack.pop();
63 * array = stack.pop();
64 * array.push(value);
65 * stack.push(array);
66 *
67 * [11] WRAP n
68 *
69 * stack.push(stack.pop(n));
70 *
71 * [12] TEXT
72 *
73 * stack.push(input.substring(stack.pop(), currPos));
74 *
75 * Conditions and Loops
76 * --------------------
77 *
78 * [13] IF t, f
79 *
80 * if (stack.top()) {
81 * interpret(ip + 3, ip + 3 + t);
82 * } else {
83 * interpret(ip + 3 + t, ip + 3 + t + f);
84 * }
85 *
86 * [14] IF_ERROR t, f
87 *
88 * if (stack.top() === FAILED) {
89 * interpret(ip + 3, ip + 3 + t);
90 * } else {
91 * interpret(ip + 3 + t, ip + 3 + t + f);
92 * }
93 *
94 * [15] IF_NOT_ERROR t, f
95 *
96 * if (stack.top() !== FAILED) {
97 * interpret(ip + 3, ip + 3 + t);
98 * } else {
99 * interpret(ip + 3 + t, ip + 3 + t + f);
100 * }
101 *
102 * [16] WHILE_NOT_ERROR b
103 *
104 * while(stack.top() !== FAILED) {
105 * interpret(ip + 2, ip + 2 + b);
106 * }
107 *
108 * Matching
109 * --------
110 *
111 * [17] MATCH_ANY a, f, ...
112 *
113 * if (input.length > currPos) {
114 * interpret(ip + 3, ip + 3 + a);
115 * } else {
116 * interpret(ip + 3 + a, ip + 3 + a + f);
117 * }
118 *
119 * [18] MATCH_STRING s, a, f, ...
120 *
121 * if (input.substr(currPos, consts[s].length) === consts[s]) {
122 * interpret(ip + 4, ip + 4 + a);
123 * } else {
124 * interpret(ip + 4 + a, ip + 4 + a + f);
125 * }
126 *
127 * [19] MATCH_STRING_IC s, a, f, ...
128 *
129 * if (input.substr(currPos, consts[s].length).toLowerCase() === consts[s]) {
130 * interpret(ip + 4, ip + 4 + a);
131 * } else {
132 * interpret(ip + 4 + a, ip + 4 + a + f);
133 * }
134 *
135 * [20] MATCH_REGEXP r, a, f, ...
136 *
137 * if (consts[r].test(input.charAt(currPos))) {
138 * interpret(ip + 4, ip + 4 + a);
139 * } else {
140 * interpret(ip + 4 + a, ip + 4 + a + f);
141 * }
142 *
143 * [21] ACCEPT_N n
144 *
145 * stack.push(input.substring(currPos, n));
146 * currPos += n;
147 *
148 * [22] ACCEPT_STRING s
149 *
150 * stack.push(consts[s]);
151 * currPos += consts[s].length;
152 *
153 * [23] FAIL e
154 *
155 * stack.push(FAILED);
156 * fail(consts[e]);
157 *
158 * Calls
159 * -----
160 *
161 * [24] LOAD_SAVED_POS p
162 *
163 * savedPos = stack[p];
164 *
165 * [25] UPDATE_SAVED_POS
166 *
167 * savedPos = currPos;
168 *
169 * [26] CALL f, n, pc, p1, p2, ..., pN
170 *
171 * value = consts[f](stack[p1], ..., stack[pN]);
172 * stack.pop(n);
173 * stack.push(value);
174 *
175 * Rules
176 * -----
177 *
178 * [27] RULE r
179 *
180 * stack.push(parseRule(r));
181 *
182 * Failure Reporting
183 * -----------------
184 *
185 * [28] SILENT_FAILS_ON
186 *
187 * silentFails++;
188 *
189 * [29] SILENT_FAILS_OFF
190 *
191 * silentFails--;
192 */
193 function generateBytecode(ast) {
194 var consts = [];
195
196 function addConst(value) {
197 var index = arrays.indexOf(consts, value);
198
199 return index === -1 ? consts.push(value) - 1 : index;
200 }
201
202 function addFunctionConst(params, code) {
203 return addConst(
204 "function(" + params.join(", ") + ") {" + code + "}"
205 );
206 }
207
208 function buildSequence() {
209 return Array.prototype.concat.apply([], arguments);
210 }
211
212 function buildCondition(condCode, thenCode, elseCode) {
213 return condCode.concat(
214 [thenCode.length, elseCode.length],
215 thenCode,
216 elseCode
217 );
218 }
219
220 function buildLoop(condCode, bodyCode) {
221 return condCode.concat([bodyCode.length], bodyCode);
222 }
223
224 function buildCall(functionIndex, delta, env, sp) {
225 var params = arrays.map(objects.values(env), function(p) { return sp - p; });
226
227 return [op.CALL, functionIndex, delta, params.length].concat(params);
228 }
229
230 function buildSimplePredicate(expression, negative, context) {
231 return buildSequence(
232 [op.PUSH_CURR_POS],
233 [op.SILENT_FAILS_ON],
234 generate(expression, {
235 sp: context.sp + 1,
236 env: objects.clone(context.env),
237 action: null
238 }),
239 [op.SILENT_FAILS_OFF],
240 buildCondition(
241 [negative ? op.IF_ERROR : op.IF_NOT_ERROR],
242 buildSequence(
243 [op.POP],
244 [negative ? op.POP : op.POP_CURR_POS],
245 [op.PUSH_UNDEFINED]
246 ),
247 buildSequence(
248 [op.POP],
249 [negative ? op.POP_CURR_POS : op.POP],
250 [op.PUSH_FAILED]
251 )
252 )
253 );
254 }
255
256 function buildSemanticPredicate(code, negative, context) {
257 var functionIndex = addFunctionConst(objects.keys(context.env), code);
258
259 return buildSequence(
260 [op.UPDATE_SAVED_POS],
261 buildCall(functionIndex, 0, context.env, context.sp),
262 buildCondition(
263 [op.IF],
264 buildSequence(
265 [op.POP],
266 negative ? [op.PUSH_FAILED] : [op.PUSH_UNDEFINED]
267 ),
268 buildSequence(
269 [op.POP],
270 negative ? [op.PUSH_UNDEFINED] : [op.PUSH_FAILED]
271 )
272 )
273 );
274 }
275
276 function buildAppendLoop(expressionCode) {
277 return buildLoop(
278 [op.WHILE_NOT_ERROR],
279 buildSequence([op.APPEND], expressionCode)
280 );
281 }
282
283 var generate = visitor.build({
284 grammar: function(node) {
285 arrays.each(node.rules, generate);
286
287 node.consts = consts;
288 },
289
290 rule: function(node) {
291 node.bytecode = generate(node.expression, {
292 sp: -1, // stack pointer
293 env: { }, // mapping of label names to stack positions
294 action: null // action nodes pass themselves to children here
295 });
296 },
297
298 named: function(node, context) {
299 var nameIndex = addConst(
300 'peg$otherExpectation("' + js.stringEscape(node.name) + '")'
301 );
302
303 /*
304 * The code generated below is slightly suboptimal because |FAIL| pushes
305 * to the stack, so we need to stick a |POP| in front of it. We lack a
306 * dedicated instruction that would just report the failure and not touch
307 * the stack.
308 */
309 return buildSequence(
310 [op.SILENT_FAILS_ON],
311 generate(node.expression, context),
312 [op.SILENT_FAILS_OFF],
313 buildCondition([op.IF_ERROR], [op.FAIL, nameIndex], [])
314 );
315 },
316
317 choice: function(node, context) {
318 function buildAlternativesCode(alternatives, context) {
319 return buildSequence(
320 generate(alternatives[0], {
321 sp: context.sp,
322 env: objects.clone(context.env),
323 action: null
324 }),
325 alternatives.length > 1
326 ? buildCondition(
327 [op.IF_ERROR],
328 buildSequence(
329 [op.POP],
330 buildAlternativesCode(alternatives.slice(1), context)
331 ),
332 []
333 )
334 : []
335 );
336 }
337
338 return buildAlternativesCode(node.alternatives, context);
339 },
340
341 action: function(node, context) {
342 var env = objects.clone(context.env),
343 emitCall = node.expression.type !== "sequence"
344 || node.expression.elements.length === 0,
345 expressionCode = generate(node.expression, {
346 sp: context.sp + (emitCall ? 1 : 0),
347 env: env,
348 action: node
349 }),
350 functionIndex = addFunctionConst(objects.keys(env), node.code);
351
352 return emitCall
353 ? buildSequence(
354 [op.PUSH_CURR_POS],
355 expressionCode,
356 buildCondition(
357 [op.IF_NOT_ERROR],
358 buildSequence(
359 [op.LOAD_SAVED_POS, 1],
360 buildCall(functionIndex, 1, env, context.sp + 2)
361 ),
362 []
363 ),
364 [op.NIP]
365 )
366 : expressionCode;
367 },
368
369 sequence: function(node, context) {
370 function buildElementsCode(elements, context) {
371 var processedCount, functionIndex;
372
373 if (elements.length > 0) {
374 processedCount = node.elements.length - elements.slice(1).length;
375
376 return buildSequence(
377 generate(elements[0], {
378 sp: context.sp,
379 env: context.env,
380 action: null
381 }),
382 buildCondition(
383 [op.IF_NOT_ERROR],
384 buildElementsCode(elements.slice(1), {
385 sp: context.sp + 1,
386 env: context.env,
387 action: context.action
388 }),
389 buildSequence(
390 processedCount > 1 ? [op.POP_N, processedCount] : [op.POP],
391 [op.POP_CURR_POS],
392 [op.PUSH_FAILED]
393 )
394 )
395 );
396 } else {
397 if (context.action) {
398 functionIndex = addFunctionConst(
399 objects.keys(context.env),
400 context.action.code
401 );
402
403 return buildSequence(
404 [op.LOAD_SAVED_POS, node.elements.length],
405 buildCall(
406 functionIndex,
407 node.elements.length,
408 context.env,
409 context.sp
410 ),
411 [op.NIP]
412 );
413 } else {
414 return buildSequence([op.WRAP, node.elements.length], [op.NIP]);
415 }
416 }
417 }
418
419 return buildSequence(
420 [op.PUSH_CURR_POS],
421 buildElementsCode(node.elements, {
422 sp: context.sp + 1,
423 env: context.env,
424 action: context.action
425 })
426 );
427 },
428
429 labeled: function(node, context) {
430 var env = objects.clone(context.env);
431
432 context.env[node.label] = context.sp + 1;
433
434 return generate(node.expression, {
435 sp: context.sp,
436 env: env,
437 action: null
438 });
439 },
440
441 text: function(node, context) {
442 return buildSequence(
443 [op.PUSH_CURR_POS],
444 generate(node.expression, {
445 sp: context.sp + 1,
446 env: objects.clone(context.env),
447 action: null
448 }),
449 buildCondition(
450 [op.IF_NOT_ERROR],
451 buildSequence([op.POP], [op.TEXT]),
452 [op.NIP]
453 )
454 );
455 },
456
457 simple_and: function(node, context) {
458 return buildSimplePredicate(node.expression, false, context);
459 },
460
461 simple_not: function(node, context) {
462 return buildSimplePredicate(node.expression, true, context);
463 },
464
465 optional: function(node, context) {
466 return buildSequence(
467 generate(node.expression, {
468 sp: context.sp,
469 env: objects.clone(context.env),
470 action: null
471 }),
472 buildCondition(
473 [op.IF_ERROR],
474 buildSequence([op.POP], [op.PUSH_NULL]),
475 []
476 )
477 );
478 },
479
480 zero_or_more: function(node, context) {
481 var expressionCode = generate(node.expression, {
482 sp: context.sp + 1,
483 env: objects.clone(context.env),
484 action: null
485 });
486
487 return buildSequence(
488 [op.PUSH_EMPTY_ARRAY],
489 expressionCode,
490 buildAppendLoop(expressionCode),
491 [op.POP]
492 );
493 },
494
495 one_or_more: function(node, context) {
496 var expressionCode = generate(node.expression, {
497 sp: context.sp + 1,
498 env: objects.clone(context.env),
499 action: null
500 });
501
502 return buildSequence(
503 [op.PUSH_EMPTY_ARRAY],
504 expressionCode,
505 buildCondition(
506 [op.IF_NOT_ERROR],
507 buildSequence(buildAppendLoop(expressionCode), [op.POP]),
508 buildSequence([op.POP], [op.POP], [op.PUSH_FAILED])
509 )
510 );
511 },
512
513 group: function(node, context) {
514 return generate(node.expression, {
515 sp: context.sp,
516 env: objects.clone(context.env),
517 action: null
518 });
519 },
520
521 semantic_and: function(node, context) {
522 return buildSemanticPredicate(node.code, false, context);
523 },
524
525 semantic_not: function(node, context) {
526 return buildSemanticPredicate(node.code, true, context);
527 },
528
529 rule_ref: function(node) {
530 return [op.RULE, asts.indexOfRule(ast, node.name)];
531 },
532
533 literal: function(node) {
534 var stringIndex, expectedIndex;
535
536 if (node.value.length > 0) {
537 stringIndex = addConst('"'
538 + js.stringEscape(
539 node.ignoreCase ? node.value.toLowerCase() : node.value
540 )
541 + '"'
542 );
543 expectedIndex = addConst(
544 'peg$literalExpectation('
545 + '"' + js.stringEscape(node.value) + '", '
546 + node.ignoreCase
547 + ')'
548 );
549
550 /*
551 * For case-sensitive strings the value must match the beginning of the
552 * remaining input exactly. As a result, we can use |ACCEPT_STRING| and
553 * save one |substr| call that would be needed if we used |ACCEPT_N|.
554 */
555 return buildCondition(
556 node.ignoreCase
557 ? [op.MATCH_STRING_IC, stringIndex]
558 : [op.MATCH_STRING, stringIndex],
559 node.ignoreCase
560 ? [op.ACCEPT_N, node.value.length]
561 : [op.ACCEPT_STRING, stringIndex],
562 [op.FAIL, expectedIndex]
563 );
564 } else {
565 stringIndex = addConst('""');
566
567 return [op.PUSH, stringIndex];
568 }
569 },
570
571 "class": function(node) {
572 var regexp, parts, regexpIndex, expectedIndex;
573
574 if (node.parts.length > 0) {
575 regexp = '/^['
576 + (node.inverted ? '^' : '')
577 + arrays.map(node.parts, function(part) {
578 return part instanceof Array
579 ? js.regexpClassEscape(part[0])
580 + '-'
581 + js.regexpClassEscape(part[1])
582 : js.regexpClassEscape(part);
583 }).join('')
584 + ']/' + (node.ignoreCase ? 'i' : '');
585 } else {
586 /*
587 * IE considers regexps /[]/ and /[^]/ as syntactically invalid, so we
588 * translate them into equivalents it can handle.
589 */
590 regexp = node.inverted ? '/^[\\S\\s]/' : '/^(?!)/';
591 }
592
593 parts = '['
594 + arrays.map(node.parts, function(part) {
595 return part instanceof Array
596 ? '["' + js.stringEscape(part[0]) + '", "' + js.stringEscape(part[1]) + '"]'
597 : '"' + js.stringEscape(part) + '"';
598 }).join(', ')
599 + ']';
600
601 regexpIndex = addConst(regexp);
602 expectedIndex = addConst(
603 'peg$classExpectation('
604 + parts + ', '
605 + node.inverted + ', '
606 + node.ignoreCase
607 + ')'
608 );
609
610 return buildCondition(
611 [op.MATCH_REGEXP, regexpIndex],
612 [op.ACCEPT_N, 1],
613 [op.FAIL, expectedIndex]
614 );
615 },
616
617 any: function() {
618 var expectedIndex = addConst('peg$anyExpectation()');
619
620 return buildCondition(
621 [op.MATCH_ANY],
622 [op.ACCEPT_N, 1],
623 [op.FAIL, expectedIndex]
624 );
625 }
626 });
627
628 generate(ast);
629 }
630
631 module.exports = generateBytecode;