Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9126041
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 17, 20262026-06-17T06:56:43+00:00 2026-06-17T06:56:43+00:00

I’m building a tree walker for an homogeneus AST (all nodes have same class),

  • 0

I’m building a tree walker for an homogeneus AST (all nodes have same class), what’s the correct way to evaluate an if statement?

My AST for if are like this:
enter image description here

I would something that when parses an IF block, evaluates sequentially his CONDBLOCK children and if one of them is true, the tree walker doesn’t evaluate the remaining.

More clearly, my tree walker is something like:

ifStat       : ^(IF { jump=false; } condition* defcond?) 
condition    : { if (jump) return retval; } ^(CONDBLOCK exp block) { jump=$exp.value; }
defcond      : ^(DEFAULT block)

My question is, if in the example $op=+ so the first CONDBLOCK must be executed, I don’t want evaluate anything else, I want execute the first CODEBLOCK and go up in my AST tree to evaluate the block after if.

Now I’ve implemented that with a flag and a check in condition rule that returns if the flag was true (that means another block is already been executed).

But return retval; completely stops the execution, I want just go up without evaluate remaining conditions. How can I do that?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-17T06:56:44+00:00Added an answer on June 17, 2026 at 6:56 am

    Any kind of runtime evaluation from an AST that involves branching or jumps is probably going to get ugly. You may want to consider converting the AST into a series of more conventional operations and execute them in sequence. It’s an extra step, but it will get you out of jams like this one and I think it’s easier to verify and to debug than an AST evaluator.

    With that out of the way, here is a way to skip evaluating subsequent condition and defcond rules. I’m sticking with the structure that you have, which means that evaluations have two distinct phases: a matching phase (exp) and an execution phase (block). This is only worth noting because the phases are handled in different parts of a subgraph and there is no natural means of jumping around, so they need to be tracked across the whole if statement.

    Here’s a simple class to manage tracking a single if evaluation:

    class Evaluation {
        boolean matched = false;
        boolean done = false;
    }
    

    When matched is true and done is false, the next block gets executed. After execution, done is set to true. When matched and done are both true, no more blocks get executed for the remainder of the if statement.

    Here are the tree parser rules to handle this:

    ifStat       
    @init { Evaluation eval = new Evaluation(); }
                 : ^(IF condition[eval]* defcond[eval]?) 
                 ;
    
    condition [Evaluation eval]
                 : ^(CONDBLOCK exp {if ($exp.value) eval.matched = true;} evalblock[eval])
                 ;
    
    defcond [Evaluation eval] 
                 : ^(DEFAULT {eval.matched = true;} evalblock[eval]) //force a match
                 ;
    
    evalblock [Evaluation eval]     
                 : {eval.matched && !eval.done}? //Only do this when a condition is matched but not yet executed
                    block                //call the execution code
                    {eval.done = true;}  //evaluation is complete.
                 | ^(CODEBLOCK .*)  //read the code subgraph (nothing gets executed)                
                 ;
    

    Here are the grammars and the code I used to test this:

    TreeEvaluator.g (combined grammar to produce an AST)

    grammar TreeEvaluator;
    
    options { 
        output = AST;
    }
    
    tokens { 
        CONDBLOCK;
        CODEBLOCK;
        DEFAULT;
    }
    
    
    compilationUnit : condition+ EOF;
    condition   : cif elif* celse? -> ^(IF cif elif* celse?);
    cif         : IF expr block -> ^(CONDBLOCK expr block);
    elif        : ELIF expr block -> ^(CONDBLOCK expr block);
    celse       : ELSE block -> ^(DEFAULT block); 
    expr        : ID EQ^ ID;
    block       : LCUR ID RCUR -> ^(CODEBLOCK ID);
    
    IF  : 'if';
    ELIF: 'elif';
    ELSE: 'else';
    LCUR: '{';
    RCUR: '}';
    EQ  : '==';
    ID  : ('a'..'z'|'A'..'Z')+;
    WS  : (' '|'\t'|'\f'|'\r'|'\n')+ {skip();};
    

    AstTreeEvaluatorParser.g (tree parser)

    tree grammar AstTreeEvaluatorParser;
    
    options { 
        output = AST;
        tokenVocab = TreeEvaluator;
        ASTLabelType = CommonTree;
    }
    
    @members { 
        private static final class Evaluation {
            boolean matched = false; 
            boolean done = false;
        }
    
        private java.util.HashMap<String, Integer> vars = new java.util.HashMap<String, Integer>();
    
        public void addVar(String name, int value){
            vars.put(name, value);
        }
    
    }
    
    compilationUnit : ifStat+;
    
    ifStat       
    @init { Evaluation eval = new Evaluation(); }
                 : ^(IF condition[eval]* defcond[eval]?) 
                 ;
    
    condition [Evaluation eval]
                 : ^(CONDBLOCK exp {if ($exp.value) eval.matched = true;} evalblock[eval])
                 ;
    
    defcond [Evaluation eval] 
                 : ^(DEFAULT {eval.matched = true;} evalblock[eval]) //force a match
                 ;
    
    evalblock [Evaluation eval]     
                 : {eval.matched && !eval.done}? //Only do this when a condition is matched but not finished 
                    block                //call the execution code
                    {eval.done = true;}  //evaluation is complete.
                 | ^(CODEBLOCK .*)  //read the code node and continue without executing
                 ;
    
    block        : ^(CODEBLOCK ID) {System.out.println("Executed " + $ID.getText());};
    
    exp returns [boolean value]
                : ^(EQ lhs=ID rhs=ID)
                    {$value = vars.get($lhs.getText()) == vars.get($rhs.getText());}
                ;
    

    TreeEvaluatorTest.java (test code)

    public class TreeEvaluatorTest {
    
        public static void main(String[] args) throws Exception {
            CharStream input = new ANTLRStringStream("if a == b {b} elif a == c {c} elif a == d {d} else {e}");
            TreeEvaluatorLexer lexer = new TreeEvaluatorLexer(input);
            CommonTokenStream tokens = new CommonTokenStream(lexer);
    
            TreeEvaluatorParser parser = new TreeEvaluatorParser(tokens);
    
            TreeEvaluatorParser.compilationUnit_return result = parser.compilationUnit();
    
            if (lexer.getNumberOfSyntaxErrors() > 0 || parser.getNumberOfSyntaxErrors() > 0){
                throw new Exception("Syntax Errors encountered!");
            }
    
            AstTreeEvaluatorParser tparser = new AstTreeEvaluatorParser(new CommonTreeNodeStream(result.getTree()));
            tparser.addVar("a", 0);
            tparser.addVar("b", 2);
            tparser.addVar("c", 3);
            tparser.addVar("d", 4);
            AstTreeEvaluatorParser.compilationUnit_return tresult = tparser.compilationUnit();
    
        }
    }
    

    The test code evaluates if a == b {b} elif a == c {c} elif a == d {d} else {e}. The id between the {}s is printed if it is evaluated. So if a == b is true, then "Executed b" will be printed.

    Variable values are assigned by calling tparser.addVar(...). In this case, a doesn’t equal any other variable, so block {e} is evaluated.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I have a text area in my form which accepts all possible characters from
Let's say I'm outputting a post title and in our database, it's Hello Y&#8217;all
I have a .ini file as follows: [playlist] numberofentries=2 File1=http://87.230.82.17:80 Title1=(#1 - 365/1400) Example
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I have just tried to save a simple *.rtf file with some websites and
I have a jquery bug and I've been looking for hours now, I can't
this is what i have right now Drawing an RSS feed into the php,
I have a small JavaScript validation script that validates inputs based on Regex. I
I have this code to decode numeric html entities to the UTF8 equivalent character.

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.