All files / src spel-expression-parser.ts

87.37% Statements 630/721
89.26% Branches 183/205
100% Functions 33/33
87.37% Lines 630/721

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 1020 1021 1022 1023 10241x 1x   1x 1x 1x 1x 1x     1x 1x 1x 1x 1x 1x 1x     1x 1x 1x 1x 1x 1x 1x 1x     1x 1x 1x     1x 1x 1x 1x     1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x         1x 1x     324x 324x   1x 5138x 5138x 5138x 5138x   1x 116x 116x 116x 1x                 1x 5283x 5283x 5283x   5283x 5283x 5283x       5283x 5283x 5283x 5283x 5283x 5283x             5283x 6376x     6376x 9x 9x 9x 9x   6345x 6376x                 5283x 6402x     6402x 6x 6x 6x 6x     6402x 20x   20x 20x 20x 20x 20x   6354x 6402x             5283x 6402x   6402x 615x 615x 615x 615x   6380x 6402x             5283x 7017x   7017x 718x 718x 718x 718x   6995x 7017x                       5283x 7735x     7735x 6x 6x 6x 6x   7707x 7735x 1136x 1136x 1136x 1136x         7735x 6x     6x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x           4x 4x 4x 4x 4x 4x 4x   6565x 7735x   5283x 7707x 7707x 7392x 7379x 6963x 6752x 6603x 6590x 6584x   7707x   5283x 1136x 1136x 315x 1136x 13x 1136x 416x 1136x 211x 1136x 149x 1136x 13x 1136x 6x 1136x 13x 1136x   1136x 1136x             5283x 8885x   8885x 1679x 1679x 1679x 1357x 1678x 306x 306x 1679x   8863x 8885x               5283x 10564x   10564x 12373x 12373x 12373x 11055x 10746x 10544x 12373x 10542x 10542x 1831x 1831x   1831x 11768x 1318x 1318x 12373x 309x 309x 12373x 204x 204x 12373x 12373x   10542x 10564x                 5283x 12399x   12399x 4x 4x 4x 4x   12373x 12399x                   5283x 16141x     16141x 2930x 2930x 2930x 2930x 2930x 2930x 2930x 2930x 2930x 2930x     16141x 1x 1x 1x     16141x 808x 808x 808x 808x     16141x 2x 2x 2x 2x     16141x 1x 1x 1x 1x   12399x 16141x         5283x 12399x   12399x 12438x     12438x             12438x             12438x 12438x 12412x 12412x 12401x 12393x 12390x 12438x   51x 51x 40x 32x 29x 51x 25x 25x 25x 25x 25x     25x   25x 8x 23x 17x 17x 3x 14x 3x 11x 17x 17x 25x 25x   26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x       26x         26x 12x 12x 26x 26x 26x             51x                                                         12438x 10x 10x 10x 10x 10x 10x     12438x                             12377x 12377x   12377x 12399x               5283x 12399x   12399x   12399x 20x 20x   12399x 2574x 2574x   12399x 8234x 8234x   12399x 5x 5x   12399x 195x 195x   12399x 5x 5x   12399x 125x 125x   12399x 6x 6x     12399x 115x 115x     12399x 12399x 36x 36x     12399x 915x 915x 915x 915x 915x     12399x 26x 26x     12399x 120x 120x   12399x 7x 7x   12399x 16x 12399x 12399x         5283x 120x   120x         120x 28x 28x 28x 28x 28x         92x 120x         5283x 92x 92x     92x   92x 92x 92x 92x 92x 92x     92x 10x 10x     92x 158x   158x 57x 57x   57x 57x 55x 55x 55x 55x 55x 55x 55x 7x 7x     55x 3x 3x 3x 3x 55x 22x 22x   55x 55x 55x     2x 2x 2x 2x 2x 57x                                                   2x 2x     158x 11x 11x 11x 11x 11x 11x   90x 90x   90x 92x   5283x 44x 44x 44x 44x 44x             5283x 115x 115x 115x     115x 2x 2x 2x 2x 2x   113x 115x             5283x 36x   36x 36x 13x 13x 36x     36x 6x 6x 6x 4x 4x 4x     4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x   2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x   29x 36x             5283x 28x 28x 28x 28x 28x         5283x 7x 7x   7x 7x 2x 2x 2x 2x   6x 6x 6x 6x 3x 3x 6x 6x   6x 7x             5283x 26x     26x 4x 4x 4x   22x     25x 7x 7x 7x   7x 5x 5x 5x 5x 5x 5x 5x   7x 7x 7x     15x 25x 28x 28x 28x 28x   15x 15x 26x             5283x 53x 53x 22x 22x 12x 12x 12x 12x 22x 53x 53x         5283x 28x 28x 28x   28x 2x 2x 2x 2x   28x 28x       5283x 142467x 142467x       142467x 142467x   5283x 29064x 29064x 29064x 29064x 29064x     29064x   5283x 6515x 6515x 11x 11x 6504x 6515x   5283x 29x 29x 5283x  
import { SpelParserConfiguration } from './spel-parser-configuration.js';
import { SpelExpression } from './spel-expression.js';
import type { SpelNodeImpl } from './ast/spel-node.js';
import { Tokenizer } from './tokenizer/tokenizer.js';
import { Token } from './tokenizer/token.js';
import { TokenKind } from './tokenizer/token-kind.js';
import { SpelParseException } from './error/spel-parse-exception.js';
import { SpelMessage } from './error/spel-message.js';
 
// AST Literal Nodes
import { NullLiteral } from './ast/literal/null-literal.js';
import { BooleanLiteral } from './ast/literal/boolean-literal.js';
import { IntLiteral } from './ast/literal/int-literal.js';
import { LongLiteral } from './ast/literal/long-literal.js';
import { RealLiteral } from './ast/literal/real-literal.js';
import { FloatLiteral } from './ast/literal/float-literal.js';
import { StringLiteral } from './ast/literal/string-literal.js';
 
// AST Reference Nodes
import { CompoundExpression } from './ast/reference/compound-expression.js';
import { VariableReference } from './ast/reference/variable-reference.js';
import { PropertyOrFieldReference } from './ast/reference/property-or-field-reference.js';
import { Indexer } from './ast/reference/indexer.js';
import { MethodReference } from './ast/reference/method-reference.js';
import { ConstructorReference } from './ast/reference/constructor-reference.js';
import { BeanReference } from './ast/reference/bean-reference.js';
import { TypeReference } from './ast/reference/type-reference.js';
 
// AST Control Flow Nodes
import { Ternary } from './ast/control-flow/ternary.js';
import { Elvis } from './ast/control-flow/elvis.js';
import { Assign } from './ast/control-flow/assign.js';
 
// AST Collection Nodes
import { InlineList } from './ast/collection/inline-list.js';
import { InlineMap } from './ast/collection/inline-map.js';
import { Selection, SelectMode } from './ast/collection/selection.js';
import { Projection } from './ast/collection/projection.js';
 
// AST Operator Nodes
import { OpPlus } from './ast/operator/op-plus.js';
import { OpMinus } from './ast/operator/op-minus.js';
import { OpMultiply } from './ast/operator/op-multiply.js';
import { OpDivide } from './ast/operator/op-divide.js';
import { OpModulus } from './ast/operator/op-modulus.js';
import { OpPower } from './ast/operator/op-power.js';
import { RangeOperator } from './ast/operator/range-operator.js';
import { OpEQ } from './ast/operator/op-eq.js';
import { OpNE } from './ast/operator/op-ne.js';
import { OpLT } from './ast/operator/op-lt.js';
import { OpLE } from './ast/operator/op-le.js';
import { OpGT } from './ast/operator/op-gt.js';
import { OpGE } from './ast/operator/op-ge.js';
import { OpAnd } from './ast/operator/op-and.js';
import { OpOr } from './ast/operator/op-or.js';
import { OpNot } from './ast/operator/op-not.js';
import { OpMatches } from './ast/operator/op-matches.js';
import { OpBetween } from './ast/operator/op-between.js';
import { OpInstanceof } from './ast/operator/op-instanceof.js';
import { OpInc } from './ast/operator/op-inc.js';
import { OpDec } from './ast/operator/op-dec.js';
 
/**
 * Parallels Spring SpelExpressionParser — public API entry point
 */
export class SpelExpressionParser {
  constructor(configuration?: SpelParserConfiguration) {
    // configuration is accepted for Spring API compatibility;
    // currently unused as all expressions are parsed with defaults.
    void configuration;
  }
 
  public parseExpression(expressionString: string): SpelExpression {
    const parser = new InternalSpelExpressionParser(expressionString);
    const ast = parser.parse();
    return new SpelExpression(expressionString, ast);
  }
 
  public parseRaw(expressionString: string): SpelNodeImpl {
    const parser = new InternalSpelExpressionParser(expressionString);
    return parser.parse();
  }
}
 
/**
 * Parallels Spring InternalSpelExpressionParser
 *
 * Recursive descent parser — following Spring SpEL operator precedence chain:
 *   Assignment → Conditional → Or → And → Equality → Relational
 *   → Additive → Multiplicative → Power → Unary → Primary
 */
export class InternalSpelExpressionParser {
  private tokens: Token[] = [];
  private pos = 0;
  private readonly expressionString: string;
 
  constructor(expressionString: string) {
    this.expressionString = expressionString;
  }
 
  // ==================== ENTRY ====================
 
  public parse(): SpelNodeImpl {
    this.tokens = new Tokenizer(this.expressionString).tokenize();
    const result = this.eatExpression();
    this.expect(TokenKind.EOF);
    return result;
  }
 
  // ==================== PRECEDENCE LEVEL 1: Assignment ====================
 
  /**
   * expression := conditional_expression ('=' expression)?
   */
  private eatExpression(): SpelNodeImpl {
    const left = this.eatConditionalExpression();
 
    // Assignment = lowest precedence, right-associative
    if (this.peek().kind === TokenKind.ASSIGN) {
      const assignToken = this.advance();
      const right = this.eatExpression();
      return new Assign(assignToken.startPos, right.endPos, left, right);
    }
 
    return left;
  }
 
  // ==================== PRECEDENCE LEVEL 2: Conditional ====================
 
  /**
   * conditional_expression := or_expression
   *                           ('?' expression ':' conditional_expression)?
   *                           ('?:' expression)?
   */
  private eatConditionalExpression(): SpelNodeImpl {
    const left = this.eatOrExpression();
 
    // Elvis: ?: (standalone token, not ? followed by :)
    if (this.peek().kind === TokenKind.ELVIS) {
      const elvisToken = this.advance();
      const right = this.eatConditionalExpression();
      return new Elvis(elvisToken.startPos, right.endPos, left, right);
    }
 
    // Ternary: ? expr : expr
    if (this.peek().kind === TokenKind.QMARK) {
      this.advance(); // consume '?'
 
      const trueExpr = this.eatExpression();
      this.expect(TokenKind.COLON);
      const falseExpr = this.eatConditionalExpression();
      return new Ternary(left.startPos, falseExpr.endPos, left, trueExpr, falseExpr);
    }
 
    return left;
  }
 
  // ==================== PRECEDENCE LEVEL 3: Logical OR ====================
 
  /**
   * or_expression := and_expression ('or' / '||' and_expression)*
   */
  private eatOrExpression(): SpelNodeImpl {
    let left = this.eatAndExpression();
 
    while (this.peek().kind === TokenKind.OR) {
      const opToken = this.advance();
      const right = this.eatAndExpression();
      left = new OpOr('||', opToken.startPos, right.endPos, left, right);
    }
 
    return left;
  }
 
  // ==================== PRECEDENCE LEVEL 4: Logical AND ====================
 
  /**
   * and_expression := relational_expression ('and' / '&&' relational_expression)*
   */
  private eatAndExpression(): SpelNodeImpl {
    let left = this.eatRelationalExpression();
 
    while (this.peek().kind === TokenKind.AND) {
      const opToken = this.advance();
      const right = this.eatRelationalExpression();
      left = new OpAnd('&&', opToken.startPos, right.endPos, left, right);
    }
 
    return left;
  }
 
  // ==================== PRECEDENCE LEVEL 5: Relational ====================
 
  /**
   * relational_expression := sum_expression
   *     ( '=='/'eq' | '!='/'ne' | '<'/'lt' | '<='/'le'
   *     | '>'/'gt' | '>='/'ge' | 'matches' | 'between' | 'instanceof'
   *     ) sum_expression
   *     | sum_expression 'between' sum_expression 'and' sum_expression
   *     | sum_expression 'instanceof' sum_expression
   */
  private eatRelationalExpression(): SpelNodeImpl {
    const left = this.eatSumExpression();
 
    // Range operator: a..b
    if (this.peek().kind === TokenKind.DOTDOT) {
      const dotdotToken = this.advance();
      const right = this.eatSumExpression();
      return new RangeOperator(dotdotToken.startPos, right.endPos, left, right);
    }
 
    const kind = this.peek().kind;
    if (this.isRelationalOp(kind)) {
      const opToken = this.advance();
      const right = this.eatSumExpression();
      return this.buildRelationalOp(opToken, left, right);
    }
 
    // 'between' has two forms:
    //   1. value between {lower, upper}  (list form)
    //   2. value between lower and upper (and form)
    if (kind === TokenKind.BETWEEN) {
      const betweenToken = this.advance();
 
      // Check if next is inline list: {lower, upper}
      if (this.peek().kind === TokenKind.LBRACE) {
        const savedPos = this.pos;
        this.advance(); // consume '{'
        if (this.peek().kind !== TokenKind.RBRACE) {
          const lower = this.eatExpression();
          if (this.peek().kind === TokenKind.COMMA) {
            this.advance(); // consume ','
            const upper = this.eatExpression();
            if (this.peek().kind === TokenKind.RBRACE) {
              this.advance(); // consume '}'
              return new OpBetween('between', betweenToken.startPos, this.pos, left, lower, upper);
            }
          }
        }
        // Not a 2-element list — backtrack
        this.pos = savedPos;
      }
 
      // Form 2: value between lower and upper
      const lower = this.eatSumExpression();
      if (this.peek().kind === TokenKind.AND) {
        this.advance(); // consume 'and'
      }
      const upper = this.eatSumExpression();
      return new OpBetween('between', betweenToken.startPos, upper.endPos, left, lower, upper);
    }
 
    return left;
  }
 
  private isRelationalOp(kind: TokenKind): boolean {
    return (
      kind === TokenKind.EQ ||
      kind === TokenKind.NE ||
      kind === TokenKind.LT ||
      kind === TokenKind.LE ||
      kind === TokenKind.GT ||
      kind === TokenKind.GE ||
      kind === TokenKind.MATCHES ||
      kind === TokenKind.INSTANCEOF
    );
  }
 
  private buildRelationalOp(opToken: Token, left: SpelNodeImpl, right: SpelNodeImpl): SpelNodeImpl {
    switch (opToken.kind) {
      case TokenKind.EQ:
        return new OpEQ('==', opToken.startPos, right.endPos, left, right);
      case TokenKind.NE:
        return new OpNE('!=', opToken.startPos, right.endPos, left, right);
      case TokenKind.LT:
        return new OpLT('<', opToken.startPos, right.endPos, left, right);
      case TokenKind.LE:
        return new OpLE('<=', opToken.startPos, right.endPos, left, right);
      case TokenKind.GT:
        return new OpGT('>', opToken.startPos, right.endPos, left, right);
      case TokenKind.GE:
        return new OpGE('>=', opToken.startPos, right.endPos, left, right);
      case TokenKind.MATCHES:
        return new OpMatches('matches', opToken.startPos, right.endPos, left, right);
      case TokenKind.INSTANCEOF:
        return new OpInstanceof('instanceof', opToken.startPos, right.endPos, left, right);
      default:
        throw this.raise(SpelMessage.OODES, TokenKind[opToken.kind]);
    }
  }
 
  // ==================== PRECEDENCE LEVEL 6: Additive ====================
 
  /**
   * sum_expression := product_expression (('+' | '-') product_expression)*
   */
  private eatSumExpression(): SpelNodeImpl {
    let left = this.eatProductExpression();
 
    while (this.peek().kind === TokenKind.PLUS || this.peek().kind === TokenKind.MINUS) {
      const opToken = this.advance();
      const right = this.eatProductExpression();
      if (opToken.kind === TokenKind.PLUS) {
        left = new OpPlus('+', opToken.startPos, right.endPos, left, right);
      } else {
        left = new OpMinus('-', opToken.startPos, right.endPos, left, right);
      }
    }
 
    return left;
  }
 
  // ==================== PRECEDENCE LEVEL 7: Multiplicative ====================
 
  /**
   * product_expression := power_expression
   *     (('*' | '/' | '%' | 'mod') power_expression)*
   */
  private eatProductExpression(): SpelNodeImpl {
    let left = this.eatPowerExpression();
 
    while (true) {
      const kind = this.peek().kind;
      if (
        kind !== TokenKind.STAR &&
        kind !== TokenKind.SLASH &&
        kind !== TokenKind.PERCENT &&
        kind !== TokenKind.MOD
      ) {
        break;
      }
      const opToken = this.advance();
      const right = this.eatPowerExpression();
 
      switch (opToken.kind) {
        case TokenKind.STAR:
          left = new OpMultiply('*', opToken.startPos, right.endPos, left, right);
          break;
        case TokenKind.SLASH:
          left = new OpDivide('/', opToken.startPos, right.endPos, left, right);
          break;
        default:
          left = new OpModulus('%', opToken.startPos, right.endPos, left, right);
          break;
      }
    }
 
    return left;
  }
 
  // ==================== PRECEDENCE LEVEL 8: Power ====================
 
  /**
   * power_expression := unary_expression ('^' / '**' power_expression)?
   *
   * Power is right-associative.
   */
  private eatPowerExpression(): SpelNodeImpl {
    const left = this.eatUnaryExpression();
 
    if (this.peek().kind === TokenKind.POWER) {
      const opToken = this.advance();
      const right = this.eatPowerExpression(); // right-associative
      return new OpPower('^', opToken.startPos, right.endPos, left, right);
    }
 
    return left;
  }
 
  // ==================== PRECEDENCE LEVEL 9: Unary ====================
 
  /**
   * unary_expression := ('-' | '+' | '!' | 'not') unary_expression
   *                    | ('++' | '--') primary_expression
   *                    | primary_expression ('++' | '--')?
   *                    | primary_expression
   */
  private eatUnaryExpression(): SpelNodeImpl {
    const kind = this.peek().kind;
 
    // Prefix: -expr
    if (kind === TokenKind.MINUS) {
      const opToken = this.advance();
      const operand = this.eatUnaryExpression();
      return new OpMinus(
        '-',
        opToken.startPos,
        operand.endPos,
        new NullLiteral(opToken.startPos, opToken.endPos),
        operand,
      );
    }
 
    // Prefix: +expr (no-op, just return operand)
    if (kind === TokenKind.PLUS) {
      this.advance();
      return this.eatUnaryExpression();
    }
 
    // Prefix: !expr / not expr
    if (kind === TokenKind.NOT) {
      const opToken = this.advance();
      const operand = this.eatUnaryExpression();
      return new OpNot('!', opToken.startPos, operand.endPos, operand);
    }
 
    // Prefix: ++expr
    if (kind === TokenKind.INC) {
      const opToken = this.advance();
      const operand = this.eatUnaryExpression();
      return new OpInc('++', opToken.startPos, operand.endPos, operand);
    }
 
    // Prefix: --expr
    if (kind === TokenKind.DEC) {
      const opToken = this.advance();
      const operand = this.eatUnaryExpression();
      return new OpDec('--', opToken.startPos, operand.endPos, operand);
    }
 
    return this.eatPostfixOrPrimary();
  }
 
  /**
   * Postfix: primary (++ | -- | .identifier | .selector | [index] | (args))
   */
  private eatPostfixOrPrimary(): SpelNodeImpl {
    let node = this.eatPrimaryExpression();
 
    while (true) {
      const kind = this.peek().kind;
 
      // Postfix: expr++
      if (kind === TokenKind.INC) {
        const opToken = this.advance();
        node = new OpInc('++', opToken.startPos, opToken.endPos, node);
        continue;
      }
 
      // Postfix: expr--
      if (kind === TokenKind.DEC) {
        const opToken = this.advance();
        node = new OpDec('--', opToken.startPos, opToken.endPos, node);
        continue;
      }
 
      // Property access: expr.identifier / expr.?identifier
      if (
        kind === TokenKind.DOT ||
        kind === TokenKind.SAFE_NAV ||
        kind === TokenKind.SELECTION ||
        kind === TokenKind.PROJECTION ||
        kind === TokenKind.SELECT_FIRST ||
        kind === TokenKind.SELECT_LAST
      ) {
        // Handle selection/projection directly as combined tokens (e.g., .?[)
        if (
          kind === TokenKind.SELECTION ||
          kind === TokenKind.PROJECTION ||
          kind === TokenKind.SELECT_FIRST ||
          kind === TokenKind.SELECT_LAST
        ) {
          const selToken = this.advance();
          let predicate: SpelNodeImpl;
          if (this.peek().kind !== TokenKind.RBRACKET) {
            predicate = this.eatExpression();
          } else {
            predicate = new BooleanLiteral(selToken.startPos, selToken.startPos, true);
          }
          this.expect(TokenKind.RBRACKET);
 
          if (kind === TokenKind.PROJECTION) {
            node = new Projection(selToken.startPos, this.pos, false, node, predicate);
          } else {
            const mode =
              kind === TokenKind.SELECT_FIRST
                ? SelectMode.FIRST
                : kind === TokenKind.SELECT_LAST
                  ? SelectMode.LAST
                  : SelectMode.ALL;
            node = new Selection(selToken.startPos, this.pos, false, node, predicate, mode);
          }
          continue;
        }
 
        const dotToken = this.advance();
        const nullSafe = dotToken.kind === TokenKind.SAFE_NAV;
        const nextToken = this.peek();
        if (nextToken.kind === TokenKind.IDENTIFIER) {
          this.advance();
          let nextNode: SpelNodeImpl = new PropertyOrFieldReference(
            nextToken.startPos,
            nextToken.endPos,
            nextToken.literal!,
          );
          if (nullSafe && nextNode instanceof PropertyOrFieldReference) {
            nextNode.nullSafe = true;
          }
          // Check for [index] or (args) after property name
          if (this.peek().kind === TokenKind.LBRACKET) {
            this.advance();
            const idx = this.eatExpression();
            this.expect(TokenKind.RBRACKET);
            nextNode = new Indexer(nextNode.startPos, this.pos, nextNode, idx);
          } else if (this.peek().kind === TokenKind.LPAREN) {
            nextNode = this.eatMethodCallForName(nextToken.startPos, nextToken.literal!);
          }
          node = new CompoundExpression(node.startPos, nextNode.endPos, node, nextNode);
          continue;
        }
        // .?[ or .![ or .$[ etc. — selection/projection
        if (
          nextToken.kind === TokenKind.SELECTION ||
          nextToken.kind === TokenKind.PROJECTION ||
          nextToken.kind === TokenKind.SELECT_FIRST ||
          nextToken.kind === TokenKind.SELECT_LAST
        ) {
          const selToken = this.advance();
          // The SELECTION/PROJECTION token already consumed the '.?[' prefix
          // eat predicate up to ']'
          let predicate: SpelNodeImpl;
          if (this.peek().kind !== TokenKind.RBRACKET) {
            predicate = this.eatExpression();
          } else {
            predicate = new BooleanLiteral(nextToken.startPos, nextToken.startPos, true);
          }
          this.expect(TokenKind.RBRACKET);
 
          if (selToken.kind === TokenKind.PROJECTION) {
            node = new Projection(selToken.startPos, this.pos, false, node, predicate);
          } else {
            const mode =
              selToken.kind === TokenKind.SELECT_FIRST
                ? SelectMode.FIRST
                : selToken.kind === TokenKind.SELECT_LAST
                  ? SelectMode.LAST
                  : SelectMode.ALL;
            node = new Selection(selToken.startPos, this.pos, false, node, predicate, mode);
          }
          continue;
        }
        throw this.raise(SpelMessage.OODES, 'identifier expected after dot');
      }
 
      // Indexer: expr[index]
      if (kind === TokenKind.LBRACKET) {
        this.advance();
        const indexExpr = this.eatExpression();
        this.expect(TokenKind.RBRACKET);
        node = new Indexer(node.startPos, this.pos, node, indexExpr);
        continue;
      }
 
      // Method call: expr(args)
      if (kind === TokenKind.LPAREN) {
        this.advance();
        const args = this.eatExpressionList();
        this.expect(TokenKind.RPAREN);
        // If node is PropertyOrFieldReference, extract name
        if (node instanceof PropertyOrFieldReference) {
          const name = node.toStringAST();
          node = new MethodReference(node.startPos, this.pos, name, ...args);
        } else {
          // Anonymous lambda call or method ref on expression
          node = new MethodReference(node.startPos, this.pos, node.toStringAST(), ...args);
        }
        continue;
      }
 
      break;
    }
 
    return node;
  }
 
  // ==================== PRIMARY ====================
 
  /**
   * primary_expression := literal | #var | #func() | @bean | T(type)
   *                     | new Type(args) | { ... } | ( expr ) | identifier
   */
  private eatPrimaryExpression(): SpelNodeImpl {
    const token = this.peek();
 
    switch (token.kind) {
      // Literals
      case TokenKind.LITERAL_NULL:
        this.advance();
        return new NullLiteral(token.startPos, token.endPos);
 
      case TokenKind.LITERAL_BOOLEAN:
        this.advance();
        return new BooleanLiteral(token.startPos, token.endPos, token.payload as boolean);
 
      case TokenKind.LITERAL_INT:
        this.advance();
        return new IntLiteral(token.startPos, token.endPos, token.payload as number);
 
      case TokenKind.LITERAL_LONG:
        this.advance();
        return new LongLiteral(token.startPos, token.endPos, token.payload as number);
 
      case TokenKind.LITERAL_DOUBLE:
        this.advance();
        return new RealLiteral(token.startPos, token.endPos, token.payload as number);
 
      case TokenKind.LITERAL_FLOAT:
        this.advance();
        return new FloatLiteral(token.startPos, token.endPos, token.payload as number);
 
      case TokenKind.LITERAL_STRING:
        this.advance();
        return new StringLiteral(token.startPos, token.endPos, token.payload as string);
 
      case TokenKind.LITERAL_HEX:
        this.advance();
        return new IntLiteral(token.startPos, token.endPos, token.payload as number);
 
      // Variable or function: #var or #func(args)
      case TokenKind.HASH: {
        return this.eatVariableOrFunction();
      }
 
      // Bean reference: @bean or &@factoryBean
      case TokenKind.AT:
      case TokenKind.AMP_AT: {
        return this.eatBeanReference();
      }
 
      // Grouping: (expr)
      case TokenKind.LPAREN: {
        this.advance();
        const expr = this.eatExpression();
        this.expect(TokenKind.RPAREN);
        return expr;
      }
 
      // Inline list or map: {a, b, c} or {key: value}
      case TokenKind.LBRACE: {
        return this.eatInlineCollection();
      }
 
      // Identifier — may be T(type), new, or compound expression
      case TokenKind.IDENTIFIER: {
        return this.eatIdentifierStart();
      }
 
      case TokenKind.NEW: {
        return this.eatConstructorReference();
      }
 
      default:
        throw this.raise(SpelMessage.OODES, token.literal!);
    }
  }
 
  /**
   * Eat identifier-based expressions: identifier | T(type) | new Type
   */
  private eatIdentifierStart(): SpelNodeImpl {
    const token = this.peek();
 
    if (token.kind !== TokenKind.IDENTIFIER) {
      throw this.raise(SpelMessage.OODES, token.literal!);
    }
 
    // T(Type) type reference
    if (token.literal === 'T' || token.literal === 't') {
      const savedPos = this.pos;
      this.advance();
      if (this.peek().kind === TokenKind.LPAREN) {
        return this.eatTypeReference();
      }
      // Not T(...), backtrack to normal identifier
      this.pos = savedPos;
    }
 
    return this.eatCompoundExpression();
  }
 
  /**
   * Compound expression: identifier (.identifier | .?identifier | [index] | (args) )*
   */
  private eatCompoundExpression(): SpelNodeImpl {
    const startToken = this.peek();
    if (startToken.kind !== TokenKind.IDENTIFIER) {
      throw this.raise(SpelMessage.OODES, startToken.literal!);
    }
    this.advance();
 
    const startPos = startToken.startPos;
    let node: SpelNodeImpl = new PropertyOrFieldReference(
      startToken.startPos,
      startToken.endPos,
      startToken.literal!,
    );
 
    // Check for method call: name(args)
    if (this.peek().kind === TokenKind.LPAREN) {
      node = this.eatMethodCallForName(startPos, startToken.literal!);
    }
 
    // Postfix chain: .prop / ?.prop / [index]
    while (true) {
      const kind = this.peek().kind;
 
      if (kind === TokenKind.DOT || kind === TokenKind.SAFE_NAV) {
        const dotToken = this.advance();
        const nullSafe = dotToken.kind === TokenKind.SAFE_NAV;
 
        const nextToken = this.peek();
        if (nextToken.kind === TokenKind.IDENTIFIER) {
          this.advance();
          let nextNode: SpelNodeImpl = new PropertyOrFieldReference(
            nextToken.startPos,
            nextToken.endPos,
            nextToken.literal!,
          );
          if (nullSafe && nextNode instanceof PropertyOrFieldReference) {
            nextNode.nullSafe = true;
          }
 
          // Check for [index] or (args) after property name
          if (this.peek().kind === TokenKind.LBRACKET) {
            this.advance();
            const idx = this.eatExpression();
            this.expect(TokenKind.RBRACKET);
            nextNode = new Indexer(nextNode.startPos, this.pos, nextNode, idx);
          } else if (this.peek().kind === TokenKind.LPAREN) {
            nextNode = this.eatMethodCallForName(nextToken.startPos, nextToken.literal!);
          }
 
          node = new CompoundExpression(node.startPos, nextNode.endPos, node, nextNode);
          continue;
        }
 
        // Selection/Projection: .?[predicate] / .![projection]
        if (
          nextToken.kind === TokenKind.SELECTION ||
          nextToken.kind === TokenKind.PROJECTION ||
          nextToken.kind === TokenKind.SELECT_FIRST ||
          nextToken.kind === TokenKind.SELECT_LAST
        ) {
          const selToken = this.advance();
          this.advance(); // Skip the consumed '['
          // The SELECTION/PROJECTION token already consumed '.?[' — eat predicate up to ']'
          let predicate: SpelNodeImpl;
          if (this.peek().kind !== TokenKind.RBRACKET) {
            predicate = this.eatExpression();
          } else {
            predicate = new BooleanLiteral(nextToken.startPos, nextToken.startPos, true);
          }
          this.expect(TokenKind.RBRACKET);
 
          if (selToken.kind === TokenKind.PROJECTION) {
            node = new Projection(selToken.startPos, this.pos, false, node, predicate);
          } else {
            const mode =
              selToken.kind === TokenKind.SELECT_FIRST
                ? SelectMode.FIRST
                : selToken.kind === TokenKind.SELECT_LAST
                  ? SelectMode.LAST
                  : SelectMode.ALL;
            node = new Selection(selToken.startPos, this.pos, false, node, predicate, mode);
          }
          continue;
        }
 
        throw this.raise(SpelMessage.OODES, 'identifier or selector expected after dot');
      }
 
      // Indexer after expression: expr[index]
      if (kind === TokenKind.LBRACKET) {
        this.advance();
        const idx = this.eatExpression();
        this.expect(TokenKind.RBRACKET);
        node = new Indexer(node.startPos, this.pos, node, idx);
        continue;
      }
 
      break;
    }
 
    return node;
  }
 
  private eatMethodCallForName(startPos: number, name: string): SpelNodeImpl {
    this.advance(); // consume '('
    const args = this.eatExpressionList();
    this.expect(TokenKind.RPAREN);
    return new MethodReference(startPos, this.pos, name, ...args);
  }
 
  // ==================== VARIABLE / FUNCTION ====================
 
  /**
   * #var or #func(args)
   */
  private eatVariableOrFunction(): SpelNodeImpl {
    const hashToken = this.advance(); // '#'
    const nameToken = this.expect(TokenKind.IDENTIFIER);
    const name = nameToken.literal!;
 
    // Function call: #func(arg1, arg2)
    if (this.peek().kind === TokenKind.LPAREN) {
      this.advance();
      const args = this.eatExpressionList();
      this.expect(TokenKind.RPAREN);
      return new MethodReference(hashToken.startPos, this.pos, name, ...args);
    }
 
    return new VariableReference(hashToken.startPos, nameToken.endPos, name);
  }
 
  // ==================== BEAN ====================
 
  /**
   * @bean or &@factoryBean
   */
  private eatBeanReference(): SpelNodeImpl {
    const atToken = this.advance();
    // &@ factory bean prefix
    let isFactoryBean = false;
    if (atToken.kind === TokenKind.AMP_AT) {
      isFactoryBean = true;
    }
    const nameToken = this.expect(TokenKind.IDENTIFIER);
 
    // Check for method call: @bean.method(args)
    if (this.peek().kind === TokenKind.DOT) {
      this.advance();
      const methodToken = this.expect(TokenKind.IDENTIFIER);
      if (this.peek().kind === TokenKind.LPAREN) {
        this.advance();
        const args = this.eatExpressionList();
        this.expect(TokenKind.RPAREN);
        // Build: #beanRef.name.method => @bean name accessed via bean resolver then method called
        // For Phase 2, return as compound: beanRef.method(args)
        const beanRef = new BeanReference(
          atToken.startPos,
          nameToken.endPos,
          nameToken.literal!,
          isFactoryBean,
        );
        const methodRef = new MethodReference(
          methodToken.startPos,
          this.pos,
          methodToken.literal!,
          ...args,
        );
        return new CompoundExpression(atToken.startPos, this.pos, beanRef, methodRef);
      }
      // @bean.property
      const beanRef = new BeanReference(
        atToken.startPos,
        nameToken.endPos,
        nameToken.literal!,
        isFactoryBean,
      );
      const propRef = new PropertyOrFieldReference(
        methodToken.startPos,
        methodToken.endPos,
        methodToken.literal!,
      );
      return new CompoundExpression(atToken.startPos, this.pos, beanRef, propRef);
    }
 
    return new BeanReference(atToken.startPos, nameToken.endPos, nameToken.literal!, isFactoryBean);
  }
 
  // ==================== TYPE ====================
 
  /**
   * T(Type) type reference
   */
  private eatTypeReference(): SpelNodeImpl {
    this.advance(); // consume '(' after T
    const typeName = this.eatQualifiedIdentifier();
    this.expect(TokenKind.RPAREN);
    return new TypeReference(this.pos, this.pos, typeName);
  }
 
  /**
   * new Type(args...) constructor reference
   */
  private eatConstructorReference(): SpelNodeImpl {
    const newToken = this.advance(); // consume 'new'
    const typeToken = this.expect(TokenKind.IDENTIFIER);
    // Read qualified type name: java.lang.String
    let className = typeToken.literal!;
    while (this.peek().kind === TokenKind.DOT) {
      this.advance();
      const next = this.advance();
      className += `.${next.literal!}`;
    }
 
    const args: SpelNodeImpl[] = [];
    if (this.peek().kind === TokenKind.LPAREN) {
      this.advance();
      if (this.peek().kind !== TokenKind.RPAREN) {
        args.push(...this.eatExpressionList());
      }
      this.expect(TokenKind.RPAREN);
    }
 
    return new ConstructorReference(newToken.startPos, this.pos, className, ...args);
  }
 
  // ==================== COLLECTION ====================
 
  /**
   * { expr, expr, ... } or { key: value, key: value, ... }
   */
  private eatInlineCollection(): SpelNodeImpl {
    const start = this.advance().startPos; // consume '{'
 
    // Empty collection
    if (this.peek().kind === TokenKind.RBRACE) {
      this.advance();
      return new InlineList(start, this.pos);
    }
 
    const first = this.eatExpression();
 
    // Map syntax: {key: value, ...}
    if (this.peek().kind === TokenKind.COLON) {
      this.advance(); // consume ':'
      const value = this.eatExpression();
      const entries: SpelNodeImpl[] = [first, value];
 
      while (this.peek().kind === TokenKind.COMMA) {
        this.advance();
        if (this.peek().kind === TokenKind.RBRACE) break;
        const key = this.eatExpression();
        this.expect(TokenKind.COLON);
        const val = this.eatExpression();
        entries.push(key, val);
      }
 
      this.expect(TokenKind.RBRACE);
      return new InlineMap(start, this.pos, ...entries);
    }
 
    // List syntax: {a, b, c}
    const elements: SpelNodeImpl[] = [first];
    while (this.peek().kind === TokenKind.COMMA) {
      this.advance();
      if (this.peek().kind === TokenKind.RBRACE) break;
      elements.push(this.eatExpression());
    }
 
    this.expect(TokenKind.RBRACE);
    return new InlineList(start, this.pos, ...elements);
  }
 
  // ==================== HELPERS ====================
 
  /**
   * Consume comma-separated expression list
   */
  private eatExpressionList(): SpelNodeImpl[] {
    const args: SpelNodeImpl[] = [];
    if (this.peek().kind !== TokenKind.RPAREN && this.peek().kind !== TokenKind.RBRACKET) {
      args.push(this.eatExpression());
      while (this.peek().kind === TokenKind.COMMA) {
        this.advance();
        if (this.peek().kind === TokenKind.RPAREN || this.peek().kind === TokenKind.RBRACKET) break;
        args.push(this.eatExpression());
      }
    }
    return args;
  }
 
  /**
   * Consume fully qualified identifier (java.lang.String)
   */
  private eatQualifiedIdentifier(): string {
    const parts: string[] = [];
    const token = this.advance();
    parts.push(token.literal!);
 
    while (this.peek().kind === TokenKind.DOT) {
      this.advance();
      const next = this.advance();
      parts.push(next.literal!);
    }
 
    return parts.join('.');
  }
 
  // ==================== UTILITY ====================
 
  private peek(offset = 0): Token {
    const index = this.pos + offset;
    if (index >= this.tokens.length) {
      const eofPos = this.expressionString.length;
      return new Token(TokenKind.EOF, eofPos, eofPos);
    }
    return this.tokens[index]!;
  }
 
  private advance(): Token {
    const token = this.tokens[this.pos];
    if (token) {
      this.pos++;
      return token;
    }
    const eofPos = this.expressionString.length;
    return new Token(TokenKind.EOF, eofPos, eofPos);
  }
 
  private expect(kind: TokenKind): Token {
    const token = this.peek();
    if (token.kind !== kind) {
      throw this.raise(SpelMessage.OODES, TokenKind[kind], TokenKind[token.kind]);
    }
    return this.advance();
  }
 
  private raise(message: SpelMessage, ...args: string[]): SpelParseException {
    return new SpelParseException(this.peek().startPos, message, ...args);
  }
}