[antlr-interest] ANTLR NUB

Andy Tripp antlr at jazillian.com
Mon Jan 21 11:37:41 PST 2008


Hi Jan,

It looks to me like you've got overlapping rules for numbers in your 
lexer rules.
Try replacing OCCURRENCE, YEAR, and DAY_OF_MONTH with a single rule for 
handling numbers:

NUMBER: ('0'..'9)*;

As for the general question of "what to do?"...
Use the "buildAST=true" option to have the ANTLR parser produce an AST.
It will look something like this:

DATE_EXPR
    FROM
          DATE "1-January-2008"
    TO
          DATE "20-January-2008"
    EXCLUDING
          PERIOD
               DATE "Monday"
               DATE "Friday"
    INCLUDING
          PERIOD
               DATE "Monday"

What I'd do is create and then modify a List of Dates
as you process the AST. Something like this:

List<Date> getValidDates(AST dateExpr) {
    Date fromDate, toDate;
    List<Date> dates = new ArrayList<Date>();
    AST from = dateExpr.getFirstChild();
    dates.add(parseDate(from.getFirstChild())); // first date in the 
List is always from date

    Date toDate = null;

    AST to = dateExpr.getNextSibling();
    if (ast.getType() == TO) {
         toDate = parseDate(from.getFirstChild())); // we have a to date
    }
    dates.addAll(expand(dates, fromDate, toDate));   // write the 
expand() method - toDate is null means "to the end of time"

    AST theRest;
    if (ast.getType() == TO) {
        theRest = to.getNextSibling();
     } else {
        theRest = to;
    }
    while (theRest != null) {
        if (theRest.getType() == EXCLUDING) {
              exclude(dates, theRest);  // write the exclude() method
        }
        if (theRest.getType() == INCLUDING) {
              include(dates, theRest);  // write the include() method
        }
        theRest = theRest.getNextSibling();
    }
    return dates;
}
       
As you can see, this is plain old boring Java code that does the simple 
"walking" of the AST.
The other, fancier, way to do it would be to use an ANTLR tree grammar.

Andy


More information about the antlr-interest mailing list