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

89.58% Statements 232/259
85.85% Branches 176/205
75% Functions 18/24
89.17% Lines 214/240

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 66341x 41x 41x 41x 41x                             41x 41x         41x 228x 72x 72x   72x   56x 5x       51x 2x       49x 2x       47x 2x       45x 1x       44x 2x       42x 3x       39x 2x       37x 3x       34x 2x       32x 2x       30x 3x       27x 2x       25x 2x       23x 3x       20x 15x       5x 1x       4x 1x       3x 1x       2x 1x       1x 1x                           16x           156x 9x 9x     9x 7x 2x       5x 1x       4x 1x       3x 1x       2x 2x                     2x       147x 1x   146x     41x 31x 31x 31x   28x               34x                                             34x     34x 34x             28x 99x 32x       67x 26x       41x         41x 34x 34x 8x 8x 8x           26x 26x 26x 26x             7x 7x 2x 2x 2x 2x           5x 1x 1x 1x 1x           4x 1x 1x 1x         3x 1x 1x 1x         2x 1x 1x 1x         1x 1x 1x 1x 1x                               28x   3x       41x       99x 99x 37x   99x 37x   99x 3x         41x       22x   22x 71x 71x   71x 14x     57x 29x 28x 3x       8x                     41x       28x 2x 2x 2x           26x             26x     41x                   41x 17x 17x 74x 26x 48x 7x 7x 7x   7x 7x 15x 15x           17x       41x       10x 33x 4x 29x 2x 2x 2x 2x     27x       41x                                   41x           41x 1x 1x       1x       40x 9x 9x             9x 9x             9x     31x                       31x   31x   31x     31x   41x     41x     15x 6x 6x   3x     3x             41x       1x                   41x       14x                   41x                           41x       1x                   41x       1x             41x                                          
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,
  RPNOperation,
  RPNUnaryOperation,
  ScriptValueAtom,
} from "./types";
import { OperatorSymbol } from "shared/lib/rpn/types";
 
const boolToInt = (val: boolean) => (val ? 1 : 0);
const zero = {
  type: "number",
  value: 0,
} as const;
 
export const optimiseScriptValue = (input: ScriptValue): ScriptValue => {
  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 if (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,
          },
        };
      }
      /* istanbul ignore next: unreachable */
      assertUnreachable(type);
    }
    return {
      ...input,
      value: optimisedValue,
    };
  } else if (input.type === "expression") {
    return optimiseScriptValue(expressionToScriptValue(input.value));
  }
  return input;
};
 
export const expressionToScriptValue = (expression: string): ScriptValue => {
  try {
    const tokens = tokenize(expression);
    const rpnTokens = shuntingYard(tokens);
 
    const stack: ScriptValue[] = [];
 
    function 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",
      };
 
      const scriptValueOperator = operatorMap[operator];
 
      /* istanbul ignore else: unreachable else branch */
      if (scriptValueOperator) {
        return scriptValueOperator;
      } else {
        assertUnreachable(scriptValueOperator);
        return "eq";
      }
    }
 
    for (const operation of rpnTokens) {
      if (operation.type === "VAR") {
        stack.push({
          type: "variable",
          value: operation.symbol.replace(/\$/g, "").replace(/^0/g, ""),
        });
      } else if (operation.type === "VAL") {
        stack.push({
          type: "number",
          value: operation.value,
        });
      } else Iif (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();
          if (value) {
            stack.push({
              type: scriptValueOperator,
              value,
            });
          }
        } else {
          const valueB = stack.pop();
          const valueA = stack.pop();
          if (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();
          if (valueA && valueB) {
            stack.push({
              type: "min",
              valueA,
              valueB,
            });
          }
        } else if (operation.function === "max") {
          const valueB = stack.pop();
          const valueA = stack.pop();
          if (valueA && valueB) {
            stack.push({
              type: "max",
              valueA,
              valueB,
            });
          }
        } else if (operation.function === "abs") {
          const value = stack.pop();
          if (value) {
            stack.push({
              type: "abs",
              value,
            });
          }
        } else if (operation.function === "rnd") {
          const value = stack.pop();
          if (value) {
            stack.push({
              type: "rnd",
              value,
            });
          }
        } else if (operation.function === "isqrt") {
          const value = stack.pop();
          if (value) {
            stack.push({
              type: "isqrt",
              value,
            });
          }
        } else if (operation.function === "atan2") {
          const valueB = stack.pop();
          const valueA = stack.pop();
          if (valueA && valueB) {
            stack.push({
              type: "atan2",
              valueA,
              valueB,
            });
          }
        } else E{
          /* istanbul ignore next: unreachable */
          assertUnreachable(operation.function);
        }
      } else E{
        /* istanbul ignore next: unreachable */
        assertUnreachable(operation);
      }
    }
 
    return stack.length === 1 ? stack[0] : zero;
  } catch (e) {
    return zero;
  }
};
 
export const walkScriptValue = (
  input: ScriptValue,
  fn: (val: ScriptValue) => void
): void => {
  fn(input);
  if ("valueA" in input && input.valueA) {
    walkScriptValue(input.valueA, fn);
  }
  if ("valueB" in input && input.valueB) {
    walkScriptValue(input.valueB, 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 ("valueA" in currentNode && "valueB" in currentNode) {
      stack.push(currentNode.valueB, currentNode.valueA);
    } else if ("value" in currentNode && isUnaryOperation(currentNode)) {
      stack.push(currentNode.value);
    }
  }
 
  return false;
};
 
export type MappedScriptValue<T> =
  | T
  | (Omit<RPNUnaryOperation, "value"> & { value: MappedScriptValue<T> })
  | (Omit<RPNOperation, "valueA" | "valueB"> & {
      valueA: MappedScriptValue<T>;
      valueB: MappedScriptValue<T>;
    });
 
export const mapScriptValueLeafNodes = <T>(
  input: ScriptValue,
  fn: (val: ScriptValueAtom) => T
): MappedScriptValue<T> => {
  if (isValueOperation(input)) {
    const mappedA = input.valueA && mapScriptValueLeafNodes(input.valueA, fn);
    const mappedB = input.valueB && mapScriptValueLeafNodes(input.valueB, fn);
    return {
      ...input,
      valueA: mappedA,
      valueB: mappedB,
    };
  }
  Iif (isUnaryOperation(input)) {
    const mapped = input.value && mapScriptValueLeafNodes(input.value, fn);
    return {
      ...input,
      value: mapped,
    };
  }
  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 const extractScriptValueVariables = (input: ScriptValue): string[] => {
  const variables: string[] = [];
  walkScriptValue(input, (val) => {
    if (val.type === "variable" && !variables.includes(val.value)) {
      variables.push(val.value);
    } else if (val.type === "expression") {
      const text = val.value;
      if (text && typeof text === "string") {
        const expressionValue = expressionToScriptValue(text);
        const expressionVariables =
          extractScriptValueVariables(expressionValue);
        for (const expressionVariable of expressionVariables) {
          if (!variables.includes(expressionVariable)) {
            variables.push(expressionVariable);
          }
        }
      }
    }
  });
  return variables;
};
 
// 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;
      if (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;
      Iif (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[]] => {
  if (input.type === "property" || input.type === "expression") {
    const localName = `local_${localsLabel}${fetchOperations.length}`;
    rpnOperations.push({
      type: "local",
      value: localName,
    });
    fetchOperations.push({
      local: localName,
      value: input,
    });
  } else if (isValueOperation(input)) {
    if (input.valueA) {
      precompileScriptValue(
        input.valueA,
        localsLabel,
        rpnOperations,
        fetchOperations
      );
    }
    if (input.valueB) {
      precompileScriptValue(
        input.valueB,
        localsLabel,
        rpnOperations,
        fetchOperations
      );
    }
    rpnOperations.push({
      type: input.type,
    });
  } else Iif (isUnaryOperation(input)) {
    Iif (input.value) {
      precompileScriptValue(
        input.value,
        localsLabel,
        rpnOperations,
        fetchOperations
      );
    }
    rpnOperations.push({
      type: input.type,
    });
  } else Iif (input.type === "true") {
    rpnOperations.push({ type: "number", value: 1 });
  } else Iif (input.type === "false") {
    rpnOperations.push({ type: "number", value: 0 });
  } else Iif (input.type === "constant") {
    rpnOperations.push({ type: "constant", value: input.value });
  } else {
    rpnOperations.push(input);
  }
  return [rpnOperations, fetchOperations];
};
 
export const sortFetchOperations = (
  input: PrecompiledValueFetch[]
): PrecompiledValueFetch[] => {
  return [...input].sort((a, b) => {
    if (a.value.type === "property" && b.value.type === "property") {
      if (a.value.target === b.value.target) {
        // Sort on Prop
        return a.value.property.localeCompare(b.value.property);
      } else {
        // Sort on Target
        return a.value.target.localeCompare(b.value.target);
      }
    }
    return a.value.type.localeCompare(b.value.type);
  });
};
 
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 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,
    },
  };
};