Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
582 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 Answer

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);
   }
 ;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...