Not logged in.  Login/Logout/Register | List snippets | | Create snippet | Upload image | Upload data

56
LINES

< > BotCompany Repo | #1035189 // ShuntingYardCore - handles operator precences while parsing [abandoned version]

JavaX fragment (include)

// TODO: unary operators
sclass ShuntingYardCore<Op> {
  new L<Operator> operatorStack;
  
  void handleEOT() {
    while (nempty(operatorStack)) {
      var o = popLast(operatorStack);
      assertNequals(o, "(");
      outputQueue.add(o);
    }
  }

  void handleToken(S token) {
    if (iTok >= l(tok)) {
      false;
    }
    
    S t = tok.get(iTok);
    bool op = isOperator(t), space = isSpacer(t);
    if (op && space) warn("Operators should not be spacers");
    
    if (eq(t, "(")) {
      finishLiteral();
      operatorStack.add(t);
    } else if (eq(t, ")")) {
      finishLiteral();
      while (!eq(last(operatorStack), "(")) {
        assertNempty(operatorStack);
        outputQueue.add(popLast(operatorStack));
      }
      popLast(operatorStack);
    } else if (op) {
      finishLiteral();
      S o1 = t, o2;
      while (!eqOneOf(o2 = last(operatorStack), "(", null)
        && (precedence(o2) > precedence(o1)
        ||  precedence(o2) == precedence(o1) && isLeftAssociative(o1))) {
          ifdef ShuntingYardParser_debug
            print("popLast");
          endifdef
          outputQueue.add(popLast(operatorStack));
        }
        
      operatorStack.add(o1);
    }
    
    true;
  }
  
  // return 0 for non-operator
  int precedence(Op op) {
    ret 1;
  }
  
  swappable bool isLeftAssociative(Op op) { true; }
}

Author comment

Began life as a copy of #1034914

download  show line numbers  debug dex  old transpilations   

Travelled to 3 computer(s): bhatertpkbcr, mowyntqkapby, mqqgnosmbjvj

No comments. add comment

-
Snippet ID: #1035189
Snippet name: ShuntingYardCore - handles operator precences while parsing [abandoned version]
Eternal ID of this version: #1035189/1
Text MD5: 5f66cde9ccfa658d331f73beda17b664
Author: stefan
Category: javax
Type: JavaX fragment (include)
Public (visible to everyone): Yes
Archived (hidden from active list): No
Created/modified: 2022-04-08 17:50:46
Source code size: 1410 bytes / 56 lines
Pitched / IR pitched: No / No
Views / Downloads: 112 / 124
Referenced in: