Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 | 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 1071x 1071x 1071x 1071x 1071x 1071x 1071x 1071x 1071x 539x 539x 539x 539x 539x 2988x 2988x 2988x 2988x 2988x 2988x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 98x 98x 98x 98x 98x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 23x 23x 23x 539x 539x 539x 539x 539x 539x 26x 26x 27x 3x 3x 2x 26x 539x 539x 539x 539x 539x 539x 539x 5196x 5196x 5196x 539x 539x 539x 539x 539x 539x 839x 839x 839x 839x 407x 407x 407x 407x 407x 407x 797x 331x 839x 539x 539x 539x 539x 539x 539x 806x 806x 806x 806x 806x 806x 62x 62x 62x 806x 806x 806x 806x 539x 539x 539x 539x 539x 539x 539x 539x 6122x 6122x 6122x 6122x 6122x 839x 6122x 6122x 2748x 24x 24x 2724x 2724x 2724x 2724x 2748x 17x 17x 17x 17x 17x 17x 17x 17x 2707x 2707x 6122x 6122x 5x 5x 8x 6x 6x 8x 3x 3x 8x 5x 5x 6122x 6122x 8x 12x 12x 8x 8x 8x 8x 6122x 6122x 36x 36x 43x 2x 2x 2x 41x 43x 3x 3x 3x 3x 3x 38x 43x 2x 2x 2x 2x 2x 36x 36x 34x 34x 6122x 6122x 869x 869x 869x 869x 869x 6x 6x 6x 6x 6x 869x 869x 6122x 6122x 51x 6122x 6122x 713x 6122x 6122x 2x 2x 2x 6122x 6122x 88x 8x 8x 80x 86x 2x 2x 78x 78x 78x 6122x 6122x 190x 190x 190x 4x 4x 186x 186x 186x 6122x 6122x 14x 6122x 6122x 52x 6122x 6122x 406x 6122x 6122x 78x 6122x 6122x 23x 23x 23x 23x 6122x 6122x 6122x 6122x 6122x 6122x 6122x 6122x 539x 539x 539x 539x 539x 539x 539x 539x 740x 740x 740x 740x 740x 740x 539x 539x 539x 539x 539x 539x 539x 539x 114x 114x 7x 7x 114x 1x 1x 1x 1x 1x 106x 114x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 51x 51x 51x 51x 51x 51x 51x 51x 168x 92x 92x 92x 92x 168x 25x 22x 22x 25x 3x 3x 3x 25x 25x 51x 51x 51x 51x 51x 51x 51x 117x 3x 3x 3x 3x 3x 3x 114x 117x 114x 117x 117x 117x 91x 91x 91x 22x 22x 22x 22x 22x 89x 117x 117x 117x 117x 22x 22x 22x 50x 50x 51x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 713x 713x 713x 713x 713x 713x 293x 293x 293x 293x 293x 288x 293x 293x 293x 293x 293x 293x 293x 293x 293x 293x 293x 293x 420x 420x 420x 654x 416x 713x 539x 539x 539x 539x 539x 539x 539x 539x 406x 406x 406x 406x 406x 406x 198x 198x 198x 198x 198x 192x 192x 198x 12x 2x 2x 12x 2x 2x 2x 2x 208x 208x 406x 406x 208x 208x 208x 208x 255x 201x 201x 96x 96x 96x 2x 2x 5x 406x 539x 539x 539x 539x 539x 539x 539x 539x 78x 78x 78x 78x 78x 78x 75x 75x 75x 75x 75x 75x 75x 75x 3x 3x 78x 78x 3x 3x 78x 78x 78x 539x 539x 539x 539x 539x 539x 539x 539x 1547x 1547x 1547x 1547x 4x 4x 4x 1543x 1547x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 1071x 1071x 539x 539x 539x 539x 539x 539x 539x 1071x 1071x 1071x 1071x 1071x 45x 45x 45x 1026x 1026x 1026x 1026x 1026x 1026x 1026x 1026x 1026x 1026x 1026x 1071x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 539x 506x 504x 504x 2x 2x 2x 2x 506x 539x 539x | /**
* @file expression.js
* @description Turns a parsed template expression into JavaScript source.
*
* ## What moved, and why
*
* Avenx used to ship every template expression, computed value and handler to
* the browser as **source text**, and evaluate it by walking an AST there. That
* put a parser, an interpreter and a scope walker in every production bundle,
* and made the cost of reading `count` a recursive dispatch rather than a
* property access.
*
* The parse is a pure function of the source, and the compiler already has the
* source. So the parse happens here, once, at build time, and what reaches the
* browser is a closure the engine itself compiled:
*
* ```text
* count * 2 → ($s) => axGet($s, "count") * 2
* item.qty → ($s) => axRead(axGet($s, "item"), "qty", false)
* items.filter(i => !i.done)
* → ($s) => axCall(axRead(axGet($s,"items"), "filter", false),
* axGet($s,"items"), [(i) => !axRead(i,"done",false)],
* "items.filter")
* ```
*
* ## The security boundary is unchanged
*
* Every gate the interpreter applied is still applied, in the same place and on
* the same terms — it is simply called rather than interpreted. A member read
* emits {@link module:lib/core/expression/ops.readMember} with the key already
* resolved, so `x['const'+'ructor']` and `x.constructor` still arrive at one
* check as one string. A call emits `callFunction`. A free identifier emits
* `readIdentifier`, which resolves scope-first and routes an allowed global
* through the tracer's substitution point.
*
* Two checks get *stronger* by moving: naming a restricted global and writing a
* forbidden static key are now build errors with a source location, rather than
* runtime refusals a developer only sees when the branch executes.
*
* ## No `eval`, by construction
*
* The emitted text is written into the component module the bundler links, so
* the engine compiles it exactly as it compiles the rest of the bundle. Nothing
* here or downstream calls `eval` or `new Function`, which is what makes "an
* Avenx page needs no 'unsafe-eval'" a property of the pipeline rather than a
* claim about it.
*
* ## Arrow parameters stop being a runtime concept
*
* The interpreter carried a `Frame` chain so a lambda parameter would not
* resolve against component state. A compiled arrow's parameters are real
* JavaScript parameters, so the engine's own scoping does that work: this
* module only has to know which names are lexically bound so it emits the bare
* name instead of a scope read.
* @module lib/compiler/codegen/expression
*/
import { parseExpression, parseExpressionProgram, ExpressionParseError } from '../../core/expression/parser.js';
import { ALLOWED_GLOBALS, RESTRICTED_GLOBALS, FORBIDDEN_KEYS, DYNAMIC_CODE_GLOBALS } from '../../core/expression/ops.js';
/**
* The local names the emitted code uses for the runtime primitives.
*
* Short, prefixed, and declared in one place so the module emitter and the
* generator cannot drift. `$s` is the scope; everything else is imported from
* the runtime.
* @type {Object<string, string>}
*/
export const RUNTIME_BINDINGS = {
scope: '$s',
read: 'axRead',
write: 'axWrite',
call: 'axCall',
construct: 'axNew',
get: 'axGet',
set: 'axSet',
typeofName: 'axTypeof',
key: 'axKey',
hasIn: 'axIn',
ambientGet: 'axGetAmbient',
ambientSet: 'axSetAmbient',
ambientTypeof: 'axTypeofAmbient',
ambientTarget: 'axAmbientTarget',
};
/**
* The named runtime imports a module containing compiled expressions needs.
* @type {string[]}
*/
export const RUNTIME_IMPORT_NAMES = [
RUNTIME_BINDINGS.read,
RUNTIME_BINDINGS.write,
RUNTIME_BINDINGS.call,
RUNTIME_BINDINGS.construct,
RUNTIME_BINDINGS.get,
RUNTIME_BINDINGS.set,
RUNTIME_BINDINGS.typeofName,
RUNTIME_BINDINGS.key,
RUNTIME_BINDINGS.hasIn,
RUNTIME_BINDINGS.ambientGet,
RUNTIME_BINDINGS.ambientSet,
RUNTIME_BINDINGS.ambientTypeof,
RUNTIME_BINDINGS.ambientTarget,
];
/**
* Whether the body being compiled is an `<action>` or `<resource>` body.
*
* Template expressions and event handlers resolve free names through
* `axGet`/`axSet`/`axTypeof`, which refuse browser globals by documented rule.
* Action and resource bodies are ordinary JavaScript and resolve them through
* the ambient primitives instead. Compilation is synchronous, so the mode is
* set for the duration of one compile call.
* @type {boolean}
*/
let ambientMode = false;
/**
* Runs a compile step in action-body mode.
* @template T
* @param {boolean} ambient - Whether free names resolve like ordinary JavaScript.
* @param {function(): T} compile - The compile step.
* @returns {T} What the step returned.
*/
function withAmbientMode(ambient, compile) {
const previous = ambientMode;
ambientMode = ambient;
try {
return compile();
} finally {
ambientMode = previous;
}
}
/**
* The runtime primitive names free identifiers resolve through in the current mode.
* @returns {{get: string, set: string, typeofName: string}} The names.
*/
function identifierBindings() {
const B = RUNTIME_BINDINGS;
return ambientMode
? { get: B.ambientGet, set: B.ambientSet, typeofName: B.ambientTypeof }
: { get: B.get, set: B.set, typeofName: B.typeofName };
}
/**
* Raised when an expression cannot be compiled.
*/
export class ExpressionCodegenError extends Error {
/**
* @param {string} message - What could not be compiled.
* @param {string} source - The expression source.
*/
constructor(message, source) {
super(message);
this.name = 'ExpressionCodegenError';
/** @type {string} */
this.source = source;
}
}
/**
* Binary operators that map straight onto JavaScript's own.
*
* `in` is absent deliberately: the interpreter coerced the right-hand side with
* `Object(right)`, and emitting a bare `in` would throw where the interpreter
* returned false.
* @type {Set<string>}
*/
const DIRECT_BINARY = new Set([
'+', '-', '*', '/', '%', '**',
'==', '!=', '===', '!==',
'<', '>', '<=', '>=',
'&', '|', '^', '<<', '>>', '>>>',
'instanceof',
]);
/**
* Unary operators that map straight onto JavaScript's own.
* @type {Set<string>}
*/
const DIRECT_UNARY = new Set(['!', '-', '+', '~', 'void']);
/**
* A lexical scope of names bound by enclosing arrow parameters.
*/
class Bound {
/**
* @param {Bound|null} parent - The enclosing binding set.
* @param {string[]} names - Names this level binds.
*/
constructor(parent, names) {
this.parent = parent;
this.names = new Set(names);
}
/**
* @param {string} name - The name to test.
* @returns {boolean} Whether any enclosing level binds it.
*/
has(name) {
let level = this;
while (level) {
if (level.names.has(name)) return true;
level = level.parent;
}
return false;
}
}
/**
* Quotes a string as a JavaScript literal.
* @param {any} value - The value to quote.
* @returns {string} The literal source.
*/
function quote(value) {
return JSON.stringify(String(value));
}
/**
* Emits a literal value.
* @param {any} value - The literal's value.
* @returns {string} The literal source.
*/
function emitLiteral(value) {
if (value === undefined) return 'undefined';
if (value === null) return 'null';
if (typeof value === 'number') {
// `Infinity` and `NaN` have no literal form that survives JSON.
if (Number.isNaN(value)) return 'NaN';
if (value === Infinity) return 'Infinity';
if (value === -Infinity) return '-Infinity';
return String(value);
}
if (typeof value === 'boolean') return String(value);
return JSON.stringify(value);
}
/**
* Describes a node for a runtime error message, matching the interpreter.
* @param {object} node - The node.
* @returns {string} A short human-readable description.
*/
function describe(node) {
switch (node.type) {
case 'Identifier': return node.name;
case 'Literal': return JSON.stringify(node.value);
case 'Chain': return describe(node.expression);
case 'Member':
return node.computed
? `${describe(node.object)}[…]`
: `${describe(node.object)}.${node.property.value}`;
case 'Call': return `${describe(node.callee)}(…)`;
default: return 'expression';
}
}
/**
* Generates JavaScript for one AST node.
* @param {object} node - The AST node.
* @param {Bound|null} bound - Names bound by enclosing arrow parameters.
* @param {string} source - The original expression, for error messages.
* @returns {string} JavaScript source for the node's value.
*/
function emit(node, bound, source) {
const B = RUNTIME_BINDINGS;
switch (node.type) {
case 'Literal':
return emitLiteral(node.value);
case 'Identifier': {
if (bound && bound.has(node.name)) {
return node.name;
}
// A restricted global can never resolve in a template, so refusing here
// turns a runtime sandbox violation into a build error that names the
// file and the line. An action body may name one; only the dynamic-code
// constructors stay refused there.
if (ambientMode ? DYNAMIC_CODE_GLOBALS.has(node.name) : RESTRICTED_GLOBALS.has(node.name)) {
throw new ExpressionCodegenError(
ambientMode
? `"${node.name}" constructs code from a string and cannot be used in an action body.`
: `"${node.name}" is a restricted global and cannot be used in a template expression. ` +
'Move the browser API into a component action and call that instead.',
source,
);
}
return `${identifierBindings().get}(${B.scope}, ${quote(node.name)})`;
}
case 'TemplateLiteral': {
let out = '""';
for (let i = 0; i < node.quasis.length; i++) {
if (node.quasis[i] !== '') {
out += ` + ${JSON.stringify(node.quasis[i])}`;
}
if (i < node.expressions.length) {
out += ` + String(${emit(node.expressions[i], bound, source)})`;
}
}
return `(${out})`;
}
case 'ArrayLiteral': {
const items = node.elements.map((element) =>
element.type === 'Spread'
? `...${emit(element.argument, bound, source)}`
: emit(element, bound, source),
);
return `[${items.join(', ')}]`;
}
case 'ObjectLiteral': {
const parts = [];
for (const property of node.properties) {
if (property.kind === 'spread') {
parts.push(`...${emit(property.value, bound, source)}`);
continue;
}
const value = emit(property.value, bound, source);
if (property.key.computed) {
// A computed key never sets the prototype, but the interpreter
// refused a forbidden one outright and that behaviour is preserved.
parts.push(`[${B.key}(${emit(property.key.node, bound, source)})]: ${value}`);
continue;
}
const name = String(property.key.node.value);
if (FORBIDDEN_KEYS.has(name)) {
throw new ExpressionCodegenError(
`Defining property "${name}" is blocked for security reasons.`,
source,
);
}
parts.push(`${quote(name)}: ${value}`);
}
return `({${parts.join(', ')}})`;
}
case 'Member': {
const object = emit(node.object, bound, source);
const key = node.computed
? emit(node.property, bound, source)
: quote(node.property.value);
if (!node.computed && FORBIDDEN_KEYS.has(String(node.property.value))) {
throw new ExpressionCodegenError(
`Access to property "${node.property.value}" is blocked for security reasons.`,
source,
);
}
return `${B.read}(${object}, ${key}, ${node.optional ? 'true' : 'false'})`;
}
case 'Chain':
return emitChain(node.expression, bound, source);
case 'Call':
return emitCall(node, bound, source);
case 'New': {
const args = emitArguments(node.args, bound, source);
return `${B.construct}(${emit(node.callee, bound, source)}, ${args}, ${quote(describe(node.callee))})`;
}
case 'Unary': {
if (node.operator === 'typeof' && node.argument.type === 'Identifier' && !(bound && bound.has(node.argument.name))) {
return `${identifierBindings().typeofName}(${B.scope}, ${quote(node.argument.name)})`;
}
const argument = emit(node.argument, bound, source);
if (node.operator === 'typeof') {
return `(typeof ${argument})`;
}
if (DIRECT_UNARY.has(node.operator)) {
return `(${node.operator === 'void' ? 'void ' : node.operator}${argument})`;
}
throw new ExpressionCodegenError(`Unsupported operator "${node.operator}"`, source);
}
case 'Binary': {
const left = emit(node.left, bound, source);
const right = emit(node.right, bound, source);
if (node.operator === 'in') {
return `${B.hasIn}(${left}, ${right})`;
}
if (DIRECT_BINARY.has(node.operator)) {
return `(${left} ${node.operator} ${right})`;
}
throw new ExpressionCodegenError(`Unsupported operator "${node.operator}"`, source);
}
case 'Logical':
return `(${emit(node.left, bound, source)} ${node.operator} ${emit(node.right, bound, source)})`;
case 'Conditional':
return `(${emit(node.test, bound, source)} ? ${emit(node.consequent, bound, source)} : ${emit(node.alternate, bound, source)})`;
case 'Assignment':
return emitAssignment(node, bound, source);
case 'Update':
return emitUpdate(node, bound, source);
case 'Arrow': {
const inner = new Bound(bound, node.params);
const body = emit(node.body, inner, source);
return `((${node.params.join(', ')}) => ${body})`;
}
case 'Sequence':
return `(${node.expressions.map((expression) => emit(expression, bound, source)).join(', ')})`;
case 'Spread':
throw new ExpressionCodegenError('A spread element is not valid here', source);
default:
throw new ExpressionCodegenError(`Unsupported expression node "${node.type}"`, source);
}
}
/**
* Emits an argument list, including spreads.
* @param {object[]} args - Argument nodes.
* @param {Bound|null} bound - Enclosing bindings.
* @param {string} source - The original expression.
* @returns {string} An array literal of the arguments.
*/
function emitArguments(args, bound, source) {
const parts = args.map((arg) =>
arg.type === 'Spread' ? `...${emit(arg.argument, bound, source)}` : emit(arg, bound, source),
);
return `[${parts.join(', ')}]`;
}
/**
* Emits a member key, refusing a forbidden one written statically.
* @param {object} node - The Member node whose key is wanted.
* @param {Bound|null} bound - Enclosing bindings.
* @param {string} source - The original expression.
* @returns {string} JavaScript source for the key.
*/
function emitMemberKey(node, bound, source) {
if (node.computed) {
return emit(node.property, bound, source);
}
if (FORBIDDEN_KEYS.has(String(node.property.value))) {
throw new ExpressionCodegenError(
`Access to property "${node.property.value}" is blocked for security reasons.`,
source,
);
}
return quote(node.property.value);
}
/**
* Emits an optional chain as one expression.
*
* `?.` short-circuits the chain it belongs to, not merely the link that carries
* it: when `user` is nullish, `user?.profile.name` is `undefined` because the
* `name` read never happens. Emitting each link on its own cannot say that --
* `axRead(axRead(user, "profile", true), "name", false)` still performs the
* second read, on `undefined`, and throws. So a chain is emitted as one body
* that returns at the link which short-circuits, leaving every link after it
* unevaluated, arguments included.
* @param {object} node - The outermost node of the chain.
* @param {Bound|null} bound - Enclosing bindings.
* @param {string} source - The original expression.
* @returns {string} JavaScript source for the chain's value.
*/
function emitChain(node, bound, source) {
const B = RUNTIME_BINDINGS;
// Walked from the outside in, so the links come out in evaluation order with
// the chain's root -- the part that is not itself a link -- left over.
const links = [];
let root = node;
for (;;) {
if (root.type === 'Member') {
links.unshift({ member: root, call: null });
root = root.object;
continue;
}
if (root.type === 'Call') {
if (root.callee.type === 'Member') {
links.unshift({ member: root.callee, call: root });
root = root.callee.object;
} else {
links.unshift({ member: null, call: root });
root = root.callee;
}
continue;
}
break;
}
const skip = (name) => `if (${name} === null || ${name} === undefined) return undefined;`;
const steps = [`let $v = ${emit(root, bound, source)};`];
for (const { member, call } of links) {
if (!member) {
if (call.optional) steps.push(skip('$v'));
steps.push(
`$v = ${B.call}($v, undefined, ${emitArguments(call.args, bound, source)}, ${quote(describe(call.callee))});`,
);
continue;
}
if (member.optional) steps.push(skip('$v'));
const key = emitMemberKey(member, bound, source);
const optional = member.optional ? 'true' : 'false';
if (!call) {
steps.push(`$v = ${B.read}($v, ${key}, ${optional});`);
continue;
}
// The receiver is read once and used twice -- as the object of the member
// read and as `this` -- so it is bound before either.
const description = quote(
member.computed
? `${describe(member.object)}[…]`
: `${describe(member.object)}.${member.property.value}`,
);
const inner = [`const $o = $v;`, `const $f = ${B.read}($o, ${key}, ${optional});`];
if (call.optional) inner.push(skip('$f'));
inner.push(`$v = ${B.call}($f, $o, ${emitArguments(call.args, bound, source)}, ${description});`);
steps.push(`{ ${inner.join(' ')} }`);
}
return `(() => { ${steps.join(' ')} return $v; })()`;
}
/**
* Emits a call, preserving the receiver for a method call.
*
* The receiver has to be evaluated once and used twice — as the object of the
* member read and as `this` — so a method call binds it to a temporary rather
* than emitting the object expression twice, which would run its side effects
* twice.
* @param {object} node - The Call node.
* @param {Bound|null} bound - Enclosing bindings.
* @param {string} source - The original expression.
* @returns {string} JavaScript source for the call.
*/
function emitCall(node, bound, source) {
const B = RUNTIME_BINDINGS;
const { callee } = node;
const args = emitArguments(node.args, bound, source);
if (callee.type === 'Member') {
const object = emit(callee.object, bound, source);
const key = callee.computed
? emit(callee.property, bound, source)
: quote(callee.property.value);
if (!callee.computed && FORBIDDEN_KEYS.has(String(callee.property.value))) {
throw new ExpressionCodegenError(
`Access to property "${callee.property.value}" is blocked for security reasons.`,
source,
);
}
const description = quote(
callee.computed ? `${describe(callee.object)}[…]` : `${describe(callee.object)}.${callee.property.value}`,
);
// `(o => …)(object)` keeps the receiver in one evaluation. The optional
// chain short-circuits before the read, exactly as `?.` does.
const short = callee.optional ? '$o === null || $o === undefined ? undefined : ' : '';
const inner = `${B.call}(${B.read}($o, ${key}, ${callee.optional ? 'true' : 'false'}), $o, ${args}, ${description})`;
const called = node.optional
? `(($f) => $f === null || $f === undefined ? undefined : ${B.call}($f, $o, ${args}, ${description}))(${B.read}($o, ${key}, ${callee.optional ? 'true' : 'false'}))`
: inner;
return `(($o) => ${short}${called})(${object})`;
}
const fn = emit(callee, bound, source);
const description = quote(describe(callee));
if (node.optional) {
return `(($f) => $f === null || $f === undefined ? undefined : ${B.call}($f, undefined, ${args}, ${description}))(${fn})`;
}
return `${B.call}(${fn}, undefined, ${args}, ${description})`;
}
/**
* Emits an assignment, routing writes through the guarded primitives.
* @param {object} node - The Assignment node.
* @param {Bound|null} bound - Enclosing bindings.
* @param {string} source - The original expression.
* @returns {string} JavaScript source for the assignment.
*/
function emitAssignment(node, bound, source) {
const B = RUNTIME_BINDINGS;
const { target, operator } = node;
const value = emit(node.value, bound, source);
if (target.type === 'Identifier') {
if (bound && bound.has(target.name)) {
// A lambda parameter is an ordinary JavaScript binding.
return `(${target.name} ${operator} ${value})`;
}
const name = quote(target.name);
const ids = identifierBindings();
const current = `${ids.get}(${B.scope}, ${name})`;
if (operator === '=') {
return `${ids.set}(${B.scope}, ${name}, ${value})`;
}
if (operator === '&&=') {
return `(($c) => $c ? ${ids.set}(${B.scope}, ${name}, ${value}) : $c)(${current})`;
}
if (operator === '||=') {
return `(($c) => $c ? $c : ${ids.set}(${B.scope}, ${name}, ${value}))(${current})`;
}
if (operator === '??=') {
return `(($c) => $c !== null && $c !== undefined ? $c : ${ids.set}(${B.scope}, ${name}, ${value}))(${current})`;
}
return `${ids.set}(${B.scope}, ${name}, (${current} ${operator.slice(0, -1)} ${value}))`;
}
const object = emit(target.object, bound, source);
const key = target.computed ? emit(target.property, bound, source) : quote(target.property.value);
if (!target.computed && FORBIDDEN_KEYS.has(String(target.property.value))) {
throw new ExpressionCodegenError(
`Writing to property "${target.property.value}" is blocked for security reasons.`,
source,
);
}
// Object and key are each evaluated once and reused, so `a[i++] += 1` does
// not advance `i` twice.
const current = `${B.read}($o, $k, false)`;
if (operator === '=') {
return `(($o, $k) => ${B.write}($o, $k, ${value}))(${object}, ${key})`;
}
if (operator === '&&=') {
return `(($o, $k) => { const $c = ${current}; return $c ? ${B.write}($o, $k, ${value}) : $c; })(${object}, ${key})`;
}
if (operator === '||=') {
return `(($o, $k) => { const $c = ${current}; return $c ? $c : ${B.write}($o, $k, ${value}); })(${object}, ${key})`;
}
if (operator === '??=') {
return `(($o, $k) => { const $c = ${current}; return $c !== null && $c !== undefined ? $c : ${B.write}($o, $k, ${value}); })(${object}, ${key})`;
}
return `(($o, $k) => ${B.write}($o, $k, (${current} ${operator.slice(0, -1)} ${value})))(${object}, ${key})`;
}
/**
* Emits `++` / `--`, preserving prefix and postfix value semantics.
* @param {object} node - The Update node.
* @param {Bound|null} bound - Enclosing bindings.
* @param {string} source - The original expression.
* @returns {string} JavaScript source for the update.
*/
function emitUpdate(node, bound, source) {
const B = RUNTIME_BINDINGS;
const { argument, operator, prefix } = node;
const delta = operator === '++' ? '+ 1' : '- 1';
if (argument.type === 'Identifier') {
if (bound && bound.has(argument.name)) {
return `(${prefix ? `${operator}${argument.name}` : `${argument.name}${operator}`})`;
}
const name = quote(argument.name);
const ids = identifierBindings();
return (
`(($c) => { const $n = $c ${delta}; ${ids.set}(${B.scope}, ${name}, $n); return ${prefix ? '$n' : '$c'}; })` +
`(Number(${ids.get}(${B.scope}, ${name})))`
);
}
const object = emit(argument.object, bound, source);
const key = argument.computed ? emit(argument.property, bound, source) : quote(argument.property.value);
if (!argument.computed && FORBIDDEN_KEYS.has(String(argument.property.value))) {
throw new ExpressionCodegenError(
`Writing to property "${argument.property.value}" is blocked for security reasons.`,
source,
);
}
return (
`(($o, $k) => { const $c = Number(${B.read}($o, $k, false)); const $n = $c ${delta}; ` +
`${B.write}($o, $k, $n); return ${prefix ? '$n' : '$c'}; })(${object}, ${key})`
);
}
/**
* Compiles one expression to a scope-taking arrow function.
* @param {string} source - The expression source.
* @returns {string} JavaScript source for `($s) => value`.
* @throws {ExpressionCodegenError} When the expression cannot be compiled.
*/
export function compileExpressionToSource(source) {
let ast;
try {
ast = parseExpression(source);
} catch (error) {
if (error instanceof ExpressionParseError) {
throw new ExpressionCodegenError(error.message, source);
}
throw error;
}
return `(${RUNTIME_BINDINGS.scope}) => (${emit(ast, null, source)})`;
}
/**
* Compiles a run of expression statements to a scope-taking arrow function.
*
* Used for inline event handlers and any action body that is a sequence of
* expressions rather than real statement syntax. The last statement's value
* is returned, matching the interpreter's `Program` node, so an event
* handler that calls an async action hands the promise back to the
* dispatcher instead of discarding it.
* @param {string} source - The statement source.
* @param {{ambient?: boolean}} [options] - `ambient: true` compiles an
* `<action>` or `<resource>` body, whose free names resolve like ordinary
* JavaScript (scope, then allowed globals, then the host global).
* @returns {string} JavaScript source for `($s) => { … }`.
* @throws {ExpressionCodegenError} When the source cannot be compiled.
*/
export function compileStatementsToSource(source, options = {}) {
return withAmbientMode(!!options.ambient, () => compileStatementRun(source));
}
/**
* Compiles a statement run in the current identifier mode.
* @param {string} source - The statement source.
* @returns {string} JavaScript source for `($s) => { … }`.
* @throws {ExpressionCodegenError} When the source cannot be compiled.
*/
function compileStatementRun(source) {
let ast;
try {
ast = parseExpressionProgram(source);
} catch (error) {
if (error instanceof ExpressionParseError) {
throw new ExpressionCodegenError(error.message, source);
}
throw error;
}
// The last statement's value is returned, matching the interpreter's
// `Program` node: an event handler that calls an async action must hand
// the promise it got back to the dispatcher, or a rejection has nowhere
// to go. Every statement in a program is an expression (anything else --
// `return`, `if`, `for` -- never parses as a program), so `return` on the
// last one is always valid.
const emitted = ast.body.map((statement) => emit(statement, null, source));
const body = emitted
.map((statement, index) => (index === emitted.length - 1 ? `return ${statement};` : `${statement};`))
.join(' ');
return `(${RUNTIME_BINDINGS.scope}) => { ${body} }`;
}
/**
* Compiles an expression, returning null rather than throwing.
* @param {string} source - The expression source.
* @returns {{code: string}|{error: string}} The generated source, or the reason.
*/
export function tryCompileExpression(source) {
try {
return { code: compileExpressionToSource(source) };
} catch (error) {
return { error: error.message };
}
}
/**
* Compiles a statement run, returning null rather than throwing.
* @param {string} source - The statement source.
* @returns {{code: string}|{error: string}} The generated source, or the reason.
*/
export function tryCompileStatements(source) {
try {
return { code: compileStatementsToSource(source) };
} catch (error) {
return { error: error.message };
}
}
/**
* The import statement a module holding a compiled class body needs.
*
* One function rather than a literal repeated at each framing site. There are
* three -- the CLI's module emitter, the Vite plugin's wrapper, and the tests
* that frame a bare class body themselves -- and when the generator started
* emitting calls to the expression primitives, every site that still wrote the
* import by hand produced a module that threw `axGet is not defined` at its
* first render. Deriving the line from the same list the generator emits
* against makes that class of drift impossible.
* @param {string} base - The base class name to import (`AvenxComponent` or `AvenxPage`).
* @param {string} [specifier] - Where the base class comes from.
* @param {string} [opsSpecifier] - Where the primitives come from, when that is
* somewhere else. A caller importing the base class straight from its own
* module -- a test does -- still has to reach the runtime index for these.
* @returns {string} The import declaration, or two.
*/
export function runtimeImportStatement(base, specifier = 'avenx-core/runtime', opsSpecifier = specifier) {
if (opsSpecifier === specifier) {
return `import { ${[base, ...RUNTIME_IMPORT_NAMES].join(', ')} } from ${JSON.stringify(specifier)};`;
}
return [
`import { ${base} } from ${JSON.stringify(specifier)};`,
`import { ${RUNTIME_IMPORT_NAMES.join(', ')} } from ${JSON.stringify(opsSpecifier)};`,
].join('\n');
}
export { ALLOWED_GLOBALS };
|