Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
576 views
in Technique[技术] by (71.8m points)

antlr - trivial problem with antlr4: text==null and no idea why

I have a grammar which worked already and i reactivated. Now it does not work any more. The point is two rules

parseRule 
@init {
   this.targets = new HashSet<Category>();
} // init 
    : (|->)? Name ( Trans '(' parseTargets ')' ) (->|)?
        {
            Category cat = new Category($Name.text);
            if ($Startup.text != null) {
                this.carGr.addStart(cat);
            }
            if ($Finish.text != null) {
                this.carGr.addStop(cat);
            }
            this.carGr.addRule(cat, targets);
        }
    ;

Very simple, neglecting the optional parts, i just parse a name and targets as follows:

parseTargets : (Name parseTargets?)
        {System.out.println("targets: "+targets);
    System.out.println("name: "+$Name.text);
    if ($Name.text != null){
    this.targets.add(new Category($Name.text));}};

I think, in each instance parsed, Name must be present and thus: $Name.text!=null. So I dont need the if. The truth is different. Who can explain me???


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As mentioned in the comments, the (|->)? is incorrect. It probably is a remnant of a v3 grammar: remove them. Also, there are references to non-existing Startup and Finish rule. The following will correctly print the contents of the Name rule to your console:

parseRule
 : Name Trans '(' parseTargets ')'
   {
     System.out.println($Name.text);
   }
 ;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...