4
votes

As an example, lets say I want to parse mostly unstructured text with single markup element, double star **. This is my ANTLR grammar:

text : (plain | tag)+ ;
plain : ~(TAG) ;

tag : TAG tag_inner TAG ;
tag_inner : ~(TAG) ;

TAG : '**' ;
TEXT : ('a'..'z' | ' ' | '.')+ ;

This grammar works just fine if the text I'm parsing is syntactically correct, that is for every opening ** there is a closing **. If there is an odd number of **s, ANTLR complains, and errors out.

How would one fix this, so that ANTLR will look ahead for a closing double star, and if there is no one treat that lone double star as plain text? I'm pretty sure ANTLR can do this and that syntactic/semantic predicates are the answer, but after an our spent reading the docs, I still can't work it out.

1

1 Answers

5
votes

This will get messy when you expand your grammar! :)

But, sure, it is possible using predicates. Here's a demo:

T.g

grammar T;

options {
  output=AST;
}

tokens {
  ROOT;
  PROPER_TAG;
}

parse
  :  text+ EOF -> ^(ROOT text+)
  ;

text
  :  (tag)=> tag // syntactic predicate here! (the `(...)=>`)
  |  plain
  |  TAG
  ;

plain
  :  ~TAG 
  ;

tag
  :  TAG plain TAG -> ^(PROPER_TAG plain)
  ;

TAG  : '**' ;
TEXT : ('a'..'z' | ' ' | '.')+ ;

Main.java

import org.antlr.runtime.*;
import org.antlr.runtime.tree.*;
import org.antlr.stringtemplate.*;

public class Main {
  public static void main(String[] args) throws Exception {
    TLexer lexer = new TLexer(new ANTLRStringStream("this **is** just **a simple** demo **."));
    TParser parser = new TParser(new CommonTokenStream(lexer));
    CommonTree tree = (CommonTree)parser.parse().getTree();
    DOTTreeGenerator gen = new DOTTreeGenerator();
    StringTemplate st = gen.toDOT(tree);
    System.out.println(st);
  }
}

Run the demo

java -cp antlr-3.3.jar org.antlr.Tool T.g
javac -cp antlr-3.3.jar *.java
java -cp .:antlr-3.3.jar Main

which will produce some DOT-output that corresponds to the following AST:

enter image description here

(image created using graphviz-dev.appspot.com)