All files / src/shared/lib/scriptValue helpers.ts

85.92% Statements 348/405
75.49% Branches 265/351
94.11% Functions 32/34
85.18% Lines 322/378

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 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020109x 109x 109x 109x 109x                           109x 109x   109x 109x         109x     1691x 428x 428x   428x   169x 20x       149x 18x       131x 4x       127x 2x       125x 1x       124x 2x       122x 3x       119x 2x       117x 3x       114x 2x       112x 2x       110x 16x       94x 15x       79x 2x       77x 3x       74x 69x       5x 1x       4x 1x       3x 1x       2x 1x       1x 1x                           259x           1263x 12x 12x     12x 9x 2x       7x 1x       6x 1x       5x 1x       4x 2x             2x 2x               3x       1251x 18x 1233x 23x         1210x     109x           71x                                               71x     71x 71x             109x 84x   84x 226x 86x     86x             140x 50x       90x 10x       80x 71x 71x 13x 13x 13x           58x 58x 58x 58x             9x 9x 2x 2x 2x 2x           7x 1x 1x 1x 1x           6x 1x 1x 1x         5x 2x 2x 2x                   3x 1x 1x 1x         2x 1x 1x 1x         1x 1x 1x 1x 1x                                                 84x     84x     109x 72x 72x 72x 69x   3x       109x       29x 29x     29x 9x   29x 9x   29x 2x   29x 2x         109x       30x   30x 93x 93x   93x 21x     72x 2x 70x 35x 35x   35x 3x       9x     109x       30x 5x           25x           25x 1x 1x             24x 3x         21x     109x 1x 1x 2x       1x               109x     49x   49x 85x 85x           85x     49x 135x 2x 133x 63x 63x 9x   70x 10x     20x   60x 38x 38x 22x 1x       49x 49x     109x 80x     109x       17x 53x 10x 43x 2x 2x 2x 2x     41x       109x       1x 2x 1x 1x             1x       109x           372x               109x           372x 16x 1x 1x 1x         1x 1x 1x                     1x 1x       1x                                                                                           15x   15x 15x 15x         15x 15x             15x 10x         5x 5x             15x 15x       15x                                                                                 356x 80x 80x             80x 80x             80x     276x 4x       272x                       272x 2x 270x   270x   270x 4x 4x             4x         266x   372x     109x     128x 15x 30x   28x     28x 2x 2x         15x 15x 15x       109x       1x                   109x       90x                   109x                           109x       1x                   109x       16x                   109x       17x             109x         16x                                 109x                           109x     372x 372x   372x     1121x                 1x 1x 1x 1x   1x 1x 1x   1x 1x 1x 1x   1x 1x         1120x             11x 11x 11x           1120x 1120x     372x    
import { wrap8Bit } from "shared/lib/helpers/8bit";
import { assertUnreachable } from "./format";
import tokenize from "shared/lib/rpn/tokenizer";
import shuntingYard from "shared/lib/rpn/shuntingYard";
import {
  PrecompiledValueRPNOperation,
  PrecompiledValueFetch,
  isValueOperation,
  ScriptValue,
  isUnaryOperation,
  ValueOperatorType,
  ValueUnaryOperatorType,
  isValueUnaryOperatorType,
  isScriptValueVariable,
  ScriptValueAtom,
  OptimisedScriptValue,
} from "./types";
import { OperatorSymbol, RPNToken } from "shared/lib/rpn/types";
import { subpxShiftForUnits } from "shared/lib/helpers/subpixels";
import { normalizeVariableId } from "shared/lib/variables/variableIds";
 
const boolToInt = (val: boolean) => (val ? 1 : 0);
const zero = {
  type: "number",
  value: 0,
} as const;
 
export const optimiseScriptValue = (
  input: ScriptValue,
): OptimisedScriptValue => {
  if (isValueOperation(input)) {
    const optimisedA = input.valueA ? optimiseScriptValue(input.valueA) : zero;
    const optimisedB = input.valueB ? optimiseScriptValue(input.valueB) : zero;
 
    if (optimisedA?.type === "number" && optimisedB?.type === "number") {
      // Can perform constant folding as both inputs are numbers
      if (input.type === "add") {
        return {
          type: "number",
          value: Math.floor(optimisedA.value + optimisedB.value),
        };
      } else if (input.type === "sub") {
        return {
          type: "number",
          value: Math.floor(optimisedA.value - optimisedB.value),
        };
      } else if (input.type === "mul") {
        return {
          type: "number",
          value: Math.floor(optimisedA.value * optimisedB.value),
        };
      } else if (input.type === "div") {
        return {
          type: "number",
          value: Math.floor(optimisedA.value / optimisedB.value),
        };
      } else if (input.type === "mod") {
        return {
          type: "number",
          value: Math.floor(optimisedA.value % optimisedB.value),
        };
      } else if (input.type === "gt") {
        return {
          type: "number",
          value: boolToInt(optimisedA.value > optimisedB.value),
        };
      } else if (input.type === "gte") {
        return {
          type: "number",
          value: boolToInt(optimisedA.value >= optimisedB.value),
        };
      } else if (input.type === "lt") {
        return {
          type: "number",
          value: boolToInt(optimisedA.value < optimisedB.value),
        };
      } else if (input.type === "lte") {
        return {
          type: "number",
          value: boolToInt(optimisedA.value <= optimisedB.value),
        };
      } else if (input.type === "eq") {
        return {
          type: "number",
          value: boolToInt(optimisedA.value === optimisedB.value),
        };
      } else if (input.type === "ne") {
        return {
          type: "number",
          value: boolToInt(optimisedA.value !== optimisedB.value),
        };
      } else if (input.type === "min") {
        return {
          type: "number",
          value: Math.min(optimisedA.value, optimisedB.value),
        };
      } else if (input.type === "max") {
        return {
          type: "number",
          value: Math.max(optimisedA.value, optimisedB.value),
        };
      } else if (input.type === "and") {
        return {
          type: "number",
          value: optimisedA.value && optimisedB.value,
        };
      } else if (input.type === "or") {
        return {
          type: "number",
          value: optimisedA.value || optimisedB.value,
        };
      } else if (input.type === "shl") {
        return {
          type: "number",
          value: optimisedA.value << optimisedB.value,
        };
      } else if (input.type === "shr") {
        return {
          type: "number",
          value: optimisedA.value >> optimisedB.value,
        };
      } else if (input.type === "bAND") {
        return {
          type: "number",
          value: optimisedA.value & optimisedB.value,
        };
      } else if (input.type === "bOR") {
        return {
          type: "number",
          value: optimisedA.value | optimisedB.value,
        };
      } else if (input.type === "bXOR") {
        return {
          type: "number",
          value: optimisedA.value ^ optimisedB.value,
        };
      } else Eif (input.type === "atan2") {
        return {
          type: "number",
          value: Math.floor(
            wrap8Bit(
              Math.atan2(optimisedA.value, optimisedB.value) * (128 / Math.PI) +
                64,
            ),
          ),
        };
      }
      /* istanbul ignore next: unreachable */
      assertUnreachable(input.type);
    }
 
    return {
      ...input,
      valueA: optimisedA,
      valueB: optimisedB,
    };
  }
  if (isUnaryOperation(input)) {
    const type = input.type;
    const optimisedValue = input.value
      ? optimiseScriptValue(input.value)
      : zero;
    if (optimisedValue?.type === "number") {
      if (type === "not") {
        return {
          type: "number",
          value: boolToInt(!optimisedValue.value),
        };
      } else if (type === "abs") {
        return {
          type: "number",
          value: Math.floor(Math.abs(optimisedValue.value)),
        };
      } else if (type === "isqrt") {
        return {
          type: "number",
          value: Math.floor(Math.sqrt(optimisedValue.value)),
        };
      } else if (type === "bNOT") {
        return {
          type: "number",
          value: ~optimisedValue.value,
        };
      } else if (type === "rnd") {
        return {
          type: "rnd",
          value: {
            type: "number",
            value: optimisedValue.value,
          },
        };
      } else Eif (type === "neg") {
        return {
          type: "number",
          value: Math.floor(-optimisedValue.value),
        };
      }
      /* istanbul ignore next: unreachable */
      assertUnreachable(type);
    }
    return {
      ...input,
      value: optimisedValue,
    };
  } else if (input.type === "expression") {
    return optimiseScriptValue(expressionToScriptValue(input.value));
  } else if (input.type === "variable" && input.index) {
    return {
      ...input,
      index: optimiseScriptValue(input.index),
    };
  }
  return input;
};
 
const mapOperator = (
  operator: OperatorSymbol,
): ValueOperatorType | ValueUnaryOperatorType => {
  const operatorMap: Record<
    OperatorSymbol,
    ValueOperatorType | ValueUnaryOperatorType
  > = {
    "/": "div",
    "*": "mul",
    "+": "add",
    "-": "sub",
    "%": "mod",
    "!": "not",
    "&": "bAND",
    "|": "bOR",
    "^": "bXOR",
    "~": "bNOT",
    "==": "eq",
    "!=": "ne",
    "<": "lt",
    "<=": "lte",
    ">": "gt",
    ">=": "gte",
    "&&": "and",
    "||": "or",
    "<<": "shl",
    ">>": "shr",
    neg: "neg",
  };
 
  const scriptValueOperator = operatorMap[operator];
 
  /* istanbul ignore else: unreachable else branch */
  if (scriptValueOperator) {
    return scriptValueOperator;
  } else {
    assertUnreachable(scriptValueOperator);
    return "eq";
  }
};
 
export const rpnTokensToScriptValue = (rpnTokens: RPNToken[]): ScriptValue => {
  const stack: ScriptValue[] = [];
 
  for (const operation of rpnTokens) {
    if (operation.type === "VAR") {
      const variableId = normalizeVariableId(
        operation.symbol.replace(/\$/g, ""),
      );
      stack.push({
        type: "variable",
        value: variableId,
        ...(operation.index && {
          index: rpnTokensToScriptValue(operation.index),
        }),
      });
    } else if (operation.type === "VAL") {
      stack.push({
        type: "number",
        value: operation.value,
      });
    } else if (operation.type === "CONST") {
      stack.push({
        type: "constant",
        value: operation.symbol,
      });
    } else if (operation.type === "OP") {
      const scriptValueOperator = mapOperator(operation.operator);
      if (isValueUnaryOperatorType(scriptValueOperator)) {
        const value = stack.pop();
        Eif (value) {
          stack.push({
            type: scriptValueOperator,
            value,
          });
        }
      } else {
        const valueB = stack.pop();
        const valueA = stack.pop();
        Eif (valueA && valueB) {
          stack.push({
            type: scriptValueOperator,
            valueA,
            valueB,
          });
        }
      }
    } else if (operation.type === "FUN") {
      if (operation.function === "min") {
        const valueB = stack.pop();
        const valueA = stack.pop();
        Eif (valueA && valueB) {
          stack.push({
            type: "min",
            valueA,
            valueB,
          });
        }
      } else if (operation.function === "max") {
        const valueB = stack.pop();
        const valueA = stack.pop();
        Eif (valueA && valueB) {
          stack.push({
            type: "max",
            valueA,
            valueB,
          });
        }
      } else if (operation.function === "abs") {
        const value = stack.pop();
        Eif (value) {
          stack.push({
            type: "abs",
            value,
          });
        }
      } else if (operation.function === "len") {
        const value = stack.pop();
        if (isScriptValueVariable(value) && value.index === undefined) {
          stack.push({
            type: "len",
            value: {
              type: "variable",
              value: value.value,
            },
          });
        } else E{
          throw new Error("len() requires an array variable");
        }
      } else if (operation.function === "rnd") {
        const value = stack.pop();
        Eif (value) {
          stack.push({
            type: "rnd",
            value,
          });
        }
      } else if (operation.function === "isqrt") {
        const value = stack.pop();
        Eif (value) {
          stack.push({
            type: "isqrt",
            value,
          });
        }
      } else if (operation.function === "atan2") {
        const valueB = stack.pop();
        const valueA = stack.pop();
        Eif (valueA && valueB) {
          stack.push({
            type: "atan2",
            valueA,
            valueB,
          });
        }
      } else Eif (operation.function === "neg") {
        const value = stack.pop();
        if (value) {
          stack.push({
            type: "sub",
            valueA: { type: "number", value: 0 },
            valueB: value,
          });
        }
      } else {
        /* istanbul ignore next: unreachable */
        assertUnreachable(operation.function);
      }
    } else E{
      /* istanbul ignore next: unreachable */
      assertUnreachable(operation);
    }
  }
 
  Iif (stack.length !== 1) {
    throw new Error("Invalid RPN expression");
  }
  return stack[0];
};
 
export const expressionToScriptValue = (expression: string): ScriptValue => {
  try {
    const tokens = tokenize(expression);
    const rpnTokens = shuntingYard(tokens);
    return rpnTokensToScriptValue(rpnTokens);
  } catch {
    return zero;
  }
};
 
export const walkScriptValue = (
  input: ScriptValue,
  fn: (val: ScriptValue) => void,
): void => {
  fn(input);
  Iif (input.type === "variable" && input.index) {
    walkScriptValue(input.index, fn);
  }
  if ("valueA" in input && input.valueA) {
    walkScriptValue(input.valueA, fn);
  }
  if ("valueB" in input && input.valueB) {
    walkScriptValue(input.valueB, fn);
  }
  if (input.type === "len") {
    walkScriptValue(input.value, fn);
  }
  if ("value" in input && input.value && isUnaryOperation(input)) {
    walkScriptValue(input.value, fn);
  }
};
 
// recursively search script value for matching node, stop iterating on first match
export const someInScriptValue = (
  input: ScriptValue,
  fn: (val: ScriptValue) => boolean,
): boolean => {
  const stack: ScriptValue[] = [input];
 
  while (stack.length > 0) {
    const currentNode = stack.pop();
    Iif (!currentNode) continue;
 
    if (fn(currentNode)) {
      return true;
    }
 
    if (currentNode.type === "variable" && currentNode.index) {
      stack.push(currentNode.index);
    } else if ("valueA" in currentNode && "valueB" in currentNode) {
      stack.push(currentNode.valueB, currentNode.valueA);
    } else Iif (currentNode.type === "len") {
      stack.push(currentNode.value);
    } else if ("value" in currentNode && isUnaryOperation(currentNode)) {
      stack.push(currentNode.value);
    }
  }
 
  return false;
};
 
export const mapScriptValue = (
  input: ScriptValue,
  fn: (val: ScriptValueAtom) => ScriptValueAtom,
): ScriptValue => {
  if (isValueOperation(input)) {
    return {
      ...input,
      valueA: mapScriptValue(input.valueA, fn),
      valueB: mapScriptValue(input.valueB, fn),
    };
  }
  Iif (isUnaryOperation(input)) {
    return {
      ...input,
      value: mapScriptValue(input.value, fn),
    };
  }
  if (input.type === "len") {
    const value = fn(input.value);
    return value.type === "variable" && !("index" in value)
      ? {
          type: "len",
          value,
        }
      : value;
  }
  if (input.type === "variable" && input.index) {
    return fn({
      ...input,
      index: mapScriptValue(input.index, fn),
    });
  }
  return fn(input);
};
 
export const extractScriptValueActorIds = (input: ScriptValue): string[] => {
  const actorIds: string[] = [];
  walkScriptValue(input, (val) => {
    Iif (val.type === "property" && !actorIds.includes(val.target)) {
      actorIds.push(val.target);
    }
  });
  return actorIds;
};
 
export type ScriptValueVariableUse = {
  id: string;
  type: "number" | "array";
};
 
export const extractScriptValueVariableUses = (
  input: ScriptValue,
): ScriptValueVariableUse[] => {
  const uses: ScriptValueVariableUse[] = [];
 
  const addUse = (id: string, type: ScriptValueVariableUse["type"]) => {
    const existingUse = uses.find((use) => use.id === id);
    Iif (existingUse) {
      if (type === "array") {
        existingUse.type = "array";
      }
      return;
    }
    uses.push({ id, type });
  };
 
  const visit = (value: ScriptValue) => {
    if (value.type === "len") {
      addUse(value.value.value, "array");
    } else if (value.type === "variable") {
      addUse(value.value, value.index ? "array" : "number");
      if (value.index) {
        visit(value.index);
      }
    } else if (value.type === "expression") {
      for (const variable of extractScriptValueVariables(
        expressionToScriptValue(value.value),
      )) {
        addUse(variable, "number");
      }
    } else if (isValueOperation(value)) {
      visit(value.valueA);
      visit(value.valueB);
    } else if (isUnaryOperation(value)) {
      visit(value.value);
    }
  };
 
  visit(input);
  return uses;
};
 
export const extractScriptValueVariables = (input: ScriptValue): string[] =>
  extractScriptValueVariableUses(input).map((use) => use.id);
 
// recursively search script value for node containing variable, stop iterating on first match
export const variableInScriptValue = (
  variable: string,
  input: ScriptValue,
): boolean => {
  return someInScriptValue(input, (val) => {
    if (val.type === "variable" && val.value === variable) {
      return true;
    } else if (val.type === "expression") {
      const text = val.value;
      Eif (text && typeof text === "string") {
        const expressionValue = expressionToScriptValue(text);
        return variableInScriptValue(variable, expressionValue);
      }
    }
    return false;
  });
};
 
export const constantInScriptValue = (
  constantId: string,
  input: ScriptValue,
): boolean => {
  return someInScriptValue(input, (val) => {
    if (val.type === "constant" && val.value === constantId) {
      return true;
    } else Iif (val.type === "expression") {
      const text = val.value;
      if (text && typeof text === "string") {
        const expressionValue = expressionToScriptValue(text);
        return constantInScriptValue(constantId, expressionValue);
      }
    }
    return false;
  });
};
 
export const precompileScriptValue = (
  input: ScriptValue,
  localsLabel = "",
  rpnOperations: PrecompiledValueRPNOperation[] = [],
  fetchOperations: PrecompiledValueFetch[] = [],
): [PrecompiledValueRPNOperation[], PrecompiledValueFetch[]] => {
  return precompileOptimisedScriptValue(
    optimiseScriptValue(input),
    localsLabel,
    rpnOperations,
    fetchOperations,
  );
};
 
export const precompileOptimisedScriptValue = (
  input: OptimisedScriptValue,
  localsLabel = "",
  rpnOperations: PrecompiledValueRPNOperation[] = [],
  fetchOperations: PrecompiledValueFetch[] = [],
): [PrecompiledValueRPNOperation[], PrecompiledValueFetch[]] => {
  if (input.type === "property") {
    if (input.target === "camera") {
      const positionPropertiesX = ["xpos", "pxpos", "spxpos"];
      const positionPropertiesY = ["ypos", "pypos", "spypos"];
      const positionProperties = [
        ...positionPropertiesX,
        ...positionPropertiesY,
      ];
 
      if (positionProperties.includes(input.property)) {
        if (positionPropertiesX.includes(input.property)) {
          rpnOperations.push({
            type: "memI16",
            value: "camera_x",
          });
        } else Eif (positionPropertiesY.includes(input.property)) {
          rpnOperations.push({
            type: "memI16",
            value: "camera_y",
          });
        }
 
        if (input.property === "xpos" || input.property === "ypos") {
          rpnOperations.push({
            type: "number",
            value: subpxShiftForUnits("tiles"),
          });
          rpnOperations.push({
            type: "shr",
          });
        } else Eif (input.property === "pxpos" || input.property === "pypos") {
          rpnOperations.push({
            type: "number",
            value: subpxShiftForUnits("pixels"),
          });
          rpnOperations.push({
            type: "shr",
          });
        }
      } else Eif (input.property === "xdeadzone") {
        rpnOperations.push({
          type: "memI8",
          value: "camera_deadzone_x",
        });
      } else if (input.property === "ydeadzone") {
        rpnOperations.push({
          type: "memI8",
          value: "camera_deadzone_y",
        });
      } else if (input.property === "xoffset") {
        rpnOperations.push({
          type: "memI8",
          value: "camera_offset_x",
        });
      } else if (input.property === "yoffset") {
        rpnOperations.push({
          type: "memI8",
          value: "camera_offset_y",
        });
      } else if (input.property === "xscroll") {
        rpnOperations.push({
          type: "memI16",
          value: "scroll_x",
        });
      } else if (input.property === "yscroll") {
        rpnOperations.push({
          type: "memI16",
          value: "scroll_y",
        });
      } else {
        throw new Error(`Unsupported property type "${input.property}"`);
      }
    } else {
      const localName = `local_${localsLabel}${fetchOperations.length}`;
 
      const positionPropertiesX = ["xpos", "pxpos", "spxpos"];
      const positionPropertiesY = ["ypos", "pypos", "spypos"];
      const positionProperties = [
        ...positionPropertiesX,
        ...positionPropertiesY,
      ];
 
      if (positionProperties.includes(input.property)) {
        fetchOperations.push({
          local: localName,
          value: {
            type: "actorPosition",
            target: input.target,
          },
        });
        if (positionPropertiesX.includes(input.property)) {
          rpnOperations.push({
            type: "local",
            value: localName,
            offset: 1,
          });
        } else Eif (positionPropertiesY.includes(input.property)) {
          rpnOperations.push({
            type: "local",
            value: localName,
            offset: 2,
          });
        }
 
        if (input.property === "xpos" || input.property === "ypos") {
          rpnOperations.push({
            type: "number",
            value: subpxShiftForUnits("tiles"),
          });
          rpnOperations.push({
            type: "shr",
          });
        } else Eif (input.property === "pxpos" || input.property === "pypos") {
          rpnOperations.push({
            type: "number",
            value: subpxShiftForUnits("pixels"),
          });
          rpnOperations.push({
            type: "shr",
          });
        }
      } else Eif (input.property === "direction") {
        fetchOperations.push({
          local: localName,
          value: {
            type: "actorDirection",
            target: input.target,
          },
        });
        rpnOperations.push({
          type: "local",
          value: localName,
        });
      } else if (input.property === "frame") {
        fetchOperations.push({
          local: localName,
          value: {
            type: "actorFrame",
            target: input.target,
          },
        });
        rpnOperations.push({
          type: "local",
          value: localName,
          offset: 1,
        });
      } else {
        throw new Error(`Unsupported property type "${input.property}"`);
      }
    }
  } else if (isValueOperation(input)) {
    Eif (input.valueA) {
      precompileScriptValue(
        input.valueA,
        localsLabel,
        rpnOperations,
        fetchOperations,
      );
    }
    Eif (input.valueB) {
      precompileScriptValue(
        input.valueB,
        localsLabel,
        rpnOperations,
        fetchOperations,
      );
    }
    rpnOperations.push({
      type: input.type,
    });
  } else if (input.type === "len") {
    rpnOperations.push({
      type: "len",
      value: input.value.value,
    });
  } else Iif (isUnaryOperation(input)) {
    if (input.value) {
      precompileScriptValue(
        input.value,
        localsLabel,
        rpnOperations,
        fetchOperations,
      );
    }
    rpnOperations.push({
      type: input.type,
    });
  } else if (input.type === "true") {
    rpnOperations.push({ type: "number", value: 1 });
  } else Iif (input.type === "false") {
    rpnOperations.push({ type: "number", value: 0 });
  } else Iif (input.type === "numberSymbol") {
    rpnOperations.push({ type: "numberSymbol", value: input.value });
  } else if (input.type === "engineField") {
    const localName = `local_${localsLabel}${fetchOperations.length}`;
    fetchOperations.push({
      local: localName,
      value: {
        type: "engineField",
        value: input.value,
      },
    });
    rpnOperations.push({
      type: "local",
      value: localName,
    });
  } else {
    rpnOperations.push(input);
  }
  return [peepholeRPN(rpnOperations), fetchOperations];
};
 
export const sortFetchOperations = (
  input: PrecompiledValueFetch[],
): PrecompiledValueFetch[] => {
  return [...input].sort((a, b) => {
    const toKey = (value: PrecompiledValueFetch): string => {
      if ("target" in value.value) {
        const symbol =
          typeof value.value.target === "string"
            ? value.value.target
            : value.value.target.symbol;
        return `${symbol}::${value.value.type}`;
      } else Eif (value.value.type === "engineField") {
        return `engineField::${value.value.value}`;
      }
      assertUnreachable(value.value);
      return "";
    };
    const aKey = toKey(a);
    const bKey = toKey(b);
    return aKey.localeCompare(bKey);
  });
};
 
export const multiplyScriptValueConst = (
  value: ScriptValue,
  num: number,
): ScriptValue => {
  return {
    type: "mul",
    valueA: value,
    valueB: {
      type: "number",
      value: num,
    },
  };
};
 
export const shiftLeftScriptValueConst = (
  value: ScriptValue,
  num: number,
): ScriptValue => {
  return {
    type: "shl",
    valueA: value,
    valueB: {
      type: "number",
      value: num,
    },
  };
};
 
export const shiftRightScriptValueConst = (
  value: ScriptValue,
  num: number,
): ScriptValue => {
  return {
    type: "shr",
    valueA: value,
    valueB: {
      type: "number",
      value: num,
    },
  };
};
 
export const addScriptValueConst = (
  value: ScriptValue,
  num: number,
): ScriptValue => {
  return {
    type: "add",
    valueA: value,
    valueB: {
      type: "number",
      value: num,
    },
  };
};
 
export const subScriptValueConst = (
  value: ScriptValue,
  num: number,
): ScriptValue => {
  return {
    type: "sub",
    valueA: value,
    valueB: {
      type: "number",
      value: num,
    },
  };
};
 
export const addScriptValueToScriptValue = (
  valueA: ScriptValue,
  valueB: ScriptValue,
): ScriptValue => {
  return {
    type: "add",
    valueA: valueA,
    valueB: valueB,
  };
};
 
export const clampScriptValueConst = (
  value: ScriptValue,
  min: number,
  max: number,
): ScriptValue => {
  return {
    type: "max",
    valueA: {
      type: "number",
      value: min,
    },
    valueB: {
      type: "min",
      valueA: {
        type: "number",
        value: max,
      },
      valueB: value,
    },
  };
};
 
export const maskScriptValueConst = (
  value: ScriptValue,
  mask: number,
): ScriptValue => {
  return {
    type: "bAND",
    valueA: value,
    valueB: {
      type: "number",
      value: mask,
    },
  };
};
 
export const peepholeRPN = (
  rpn: PrecompiledValueRPNOperation[],
): PrecompiledValueRPNOperation[] => {
  const optimised: PrecompiledValueRPNOperation[] = [];
  let i = 0;
 
  while (i < rpn.length) {
    // Match SHR X + Add/Sub Y + SHL X
    // commonly used in calculations involving adding tiles/pixels values to subpixel variables
    if (
      i + 5 < rpn.length &&
      rpn[i].type === "number" &&
      rpn[i + 1].type === "shr" &&
      rpn[i + 2].type === "number" &&
      (rpn[i + 3].type === "add" || rpn[i + 3].type === "sub") &&
      rpn[i + 4].type === "number" &&
      rpn[i + 5].type === "shl"
    ) {
      const shrAmount = (rpn[i] as { value: number }).value;
      const addAmount = (rpn[i + 2] as { value: number }).value;
      const op = rpn[i + 3];
      const shlAmount = (rpn[i + 4] as { value: number }).value;
 
      Eif (shrAmount === shlAmount) {
        const combined = addAmount << shlAmount;
        const mask = ~((1 << shlAmount) - 1) & 0xffff;
 
        optimised.push({ type: "number", value: combined });
        optimised.push(op);
        optimised.push({ type: "number", value: mask });
        optimised.push({ type: "bAND" });
 
        i += 6;
        continue;
      }
    }
 
    // SHR N followed by SHL N = noop
    if (
      i + 3 < rpn.length &&
      rpn[i].type === "number" &&
      rpn[i + 1].type === "shr" &&
      rpn[i + 2].type === "number" &&
      rpn[i + 3].type === "shl"
    ) {
      const shrAmount = (rpn[i] as { value: number }).value;
      const shlAmount = (rpn[i + 2] as { value: number }).value;
      Iif (shrAmount === shlAmount) {
        i += 4;
        continue;
      }
    }
 
    optimised.push(rpn[i]);
    i++;
  }
 
  return optimised;
};