我编写了一个语法测试,在构造函数中是一个被执行两次的打印。我该如何解决?
首先,这是语法:
grammar simple_grail;
prog: tag_block ;
tag_block: tag*;
/* root definition of any tag in Grail */
tag:
p | div | canvas | rect | button | txt | textlit;
p: '<' 'p' CLASS_NAME? '>' tag_block '<' '/' 'p' '>' ;
div: '<' 'div' CLASS_NAME? '>' tag_block '<' '/' 'div' '>' ;
canvas: '<' 'canvas' CLASS_NAME? '>' tag_block '<' '/' 'canvas' '>' ;
rect:
'<' 'rect' CLASS_NAME?
'x' ASSIGN_COORD 'y' ASSIGN_COORD 'w' ASSIGN_COORD 'h' ASSIGN_COORD
'/>' ;
button:
'<' 'button' CLASS_NAME? (NAME)? 'text' ASSIGN_TEXT '/>' ;
txt:
'<' 'text' 'x' ASSIGN_COORD 'y' ASSIGN_COORD '/>' ;
textlit:
TEXT
;
CLASS_NAME: [a-zA-Z_] [a-zA-Z_0-9]* ;
ASSIGN_COORD: '=' [0-9]+ ;
name: 'name' '=' NAME ;
NAME: [A-Za-z_][A-Za-z_0-9]* ;
ASSIGN_TEXT: '=' ('"' [^"]* '"' | '\'' [^']* '\'');
TEXT: ~[<]+ ;
SimpleGrailParser 的相关部分是:
public class simple_grailTagsImpl {
@Override public void enterProg(simple_grailParser.ProgContext ctx) {
numInstructions = 0;
numInts = 0;
numFloats = 0;
numStrings = 0;
System.out.println("Starting program size=0");
}
}
加载它的主程序在这里。不知何故,它两次输入语法的主要规则
Starting program size=0
Starting program size=0
import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.tree.*;
public class SimpleGrailParser {
public static void main(String[] args) {
String text = "<p>text is here</p>";
simple_grailLexer lexer = new simple_grailLexer(CharStreams.fromString(text));
CommonTokenStream tokens = new CommonTokenStream(lexer);
simple_grailParser parser = new simple_grailParser(tokens);
simple_grailTagsImpl listener= new simple_grailTagsImpl();
parser.addParseListener(listener);
ParseTree tree = parser.prog();
ParseTreeWalker.DEFAULT.walk(listener, tree);
}
}
删除
parser.addParseListener(listener)
:这会导致重复。ParseTreeWalker.DEFAULT.walk(listener, tree)
就足够了(或删除ParseTreeWalker.DEFAULT...
)。所以,要么这样:
或这个: