[antlr-interest] skipping evaluation of some AST nodes

Mark Volkmann r.mark.volkmann at gmail.com
Wed Nov 28 08:01:06 PST 2007


On 11/28/07, Harald Mueller <harald_m_mueller at gmx.de> wrote:
> Hi again -
>
> my second gut feeling says that you can do the following:
>
> rule
>     { ... compResult; }
>    : ^(a
>        b    { compResult = some-action; }
>        c[compResult]
>       )
>    ;
>
> - i.e. you must run through everything; but you can compute things along your way and then pass them into subsequent subtree traversals (or even out to someone else via a returns or an "out" object).
>
> What you cannot do, is change the order: Left things are traversed before right things. So if you want to have a representation of perl's statements
>
>     statement if condition;
>
> or
>
>     statement unless condition;
>
> you must make sure that the condition subtree is to the *left* of the statement subtree - but that's easy.

Thanks Harald! I'm glad you had a second gut feeling! I got the
following to work using your suggestion. It still uses one kind of
global variable, value. Other than that issue, do you see anything
else that could be improved?

tree grammar MathScriptTree;

options {
	ASTLabelType = CommonTree;
	tokenVocab = MathScript;
	output = template;
}

@header {
  package com.ociweb.mathscript;
}

@members {
  int value;

  private static int toInt(CommonTree node) {
    return Integer.parseInt(node.getText());
  }
}

script: ^(SCRIPT statement*);

statement
  : simpleStatement[true]
  | ^('IF' b=condition simpleStatement[$b.result])
  ;

simpleStatement[boolean b]
	: ^('ADD' n=NUMBER) { if ($b) value += toInt(n); }
	| ^('SUBTRACT' n=NUMBER) { if ($b) value -= toInt(n); }
	| 'PRINT' { if ($b) System.out.println(value); }
	;

condition returns [boolean result]
  : 'POSITIVE' { $result = value > 0; }
  | 'NEGATIVE' { $result = value < 0; }
  | ^('<' n=NUMBER) { $result = value < toInt(n); }
  | ^('>' n=NUMBER) { $result = value > toInt(n); }
  | ^('=' n=NUMBER) { $result = value == toInt(n); }
  ;

-- 
R. Mark Volkmann
Object Computing, Inc.


More information about the antlr-interest mailing list