6

It seems that sometimes the Antlr lexer makes a bad choice on which rule to use when tokenizing a stream of characters... I'm trying to figure out how to help Antlr make the obvious-to-a-human right choice. I want to parse text like this:

d/dt(x)=a
a=d/dt
d=3
dt=4

This is an unfortunate syntax that an existing language uses and I'm trying to write a parser for. The "d/dt(x)" is representing the left hand side of a differential equation. Ignore the lingo if you must, just know that it is not "d" divided by "dt". However, the second occurrence of "d/dt" really is "d" divided by "dt".

Here's my grammar:

grammar diffeq_grammar;

program :   (statement? NEWLINE)*;

statement
    :   diffeq
    |   assignment;

diffeq  :   DDT ID ')' '=' ID;

assignment
    :   ID '=' NUMBER
    |   ID '=' ID '/' ID
    ;

DDT :   'd/dt(';
ID  :   'a'..'z'+;
NUMBER  :   '0'..'9'+;
NEWLINE :   '\r\n'|'\r'|'\n';

When using this grammar the lexer grabs the first "d/dt(" and turns it to the token DDT. Perfect! Now later the lexer sees the second "d" followed by a "/" and says "hmmm, I can match this as an ID and a '/' or I can be greedy and match DDT". The lexer chooses to be greedy... but little does it know, there is no "(" a few characters later in the input stream. When the lexer looks for the missing "(" it throws a MismatchedTokenException!

The only solution I've found so far, is to move all the rules into the parser with a grammar like:

grammar diffeq_grammar;

program :   (statement? NEWLINE)*;

statement
    :   diffeq
    |   assignment;

diffeq  :   ddt id ')' '=' id;

assignment
    :   id '=' number
    |   id '=' id '/' id
    ;

ddt :   'd' '/' 'd' 't' '(';
id  :   CHAR+;
number  :   DIGIT+;
CHAR    :   'a'..'z';
DIGIT   :   '0'..'9';
NEWLINE :   '\r\n'|'\r'|'\n';

This is a fine solution if I didn't already have thousands of lines of working code that depend on the first grammar working. After spending 2 days researching this problem I have come to the conclusion that a lexer... really ought to be able to distinguish the two cases. At some point the Antlr lexer is deciding between two rules: DDT and ID. It chooses DDT because the lexer is greedy. But when matching DDT fails, I'd like the lexer to go back to using ID.

I'm okay with using predicates or other tricks as long as the grammar remains basically the same (i.e., the rules in the lexer, stay in the lexer. And most rules are left untouched.).

Ideally I can modify the lexer rule for DDT with any valid Antlr code... and be done.

My target language is Java.

Thanks!

UPDATE

Thank you guys for some great answers!! I accepted the answer that best fit my question. The actual solution I used is in my own answer (not the accepted answer), and there are more answers that could have worked. Readers, check out all the answers; some of them may suit your case better than mine.

Jason
  • 11,709
  • 9
  • 66
  • 82

3 Answers3

5

I'm okay with using predicates or other tricks as long as the grammar remains basically the same (i.e., the rules in the lexer, stay in the lexer. And most rules are left untouched.).

In that case, force the lexer to look ahead in the char-stream to make sure there really is "d/dt(" using a gated syntactic predicate.

A demo:

grammar diffeq_grammar;

@parser::members {
  public static void main(String[] args) throws Exception {
    String src = 
        "d/dt(x)=a\n" +
        "a=d/dt\n" +
        "d=3\n" +
        "dt=4\n";
    diffeq_grammarLexer lexer = new diffeq_grammarLexer(new ANTLRStringStream(src));
    diffeq_grammarParser parser = new diffeq_grammarParser(new CommonTokenStream(lexer));
    parser.program();
  }
}

@lexer::members {
  private boolean ahead(String text) {
    for(int i = 0; i < text.length(); i++) {
      if(input.LA(i + 1) != text.charAt(i)) {
        return false;
      }
    }
    return true;
  }
}

program
 : (statement? NEWLINE)* EOF
 ;

statement
 : diffeq     {System.out.println("diffeq     : " + $text);}
 | assignment {System.out.println("assignment : " + $text);}
 ;

diffeq
 : DDT ID ')' '=' ID
 ;

assignment
 : ID '=' NUMBER
 | ID '=' ID '/' ID
 ;

DDT     : {ahead("d/dt(")}?=> 'd/dt(';
ID      : 'a'..'z'+;
NUMBER  : '0'..'9'+;
NEWLINE : '\r\n' | '\r' | '\n';

If you now run the demo:

java -cp antlr-3.3.jar org.antlr.Tool diffeq_grammar.g
javac -cp antlr-3.3.jar *.java
java -cp .:antlr-3.3.jar diffeq_grammarParser

(when using Windows, replace the : with ; in the last command)

you will see the following output:

diffeq     : d/dt(x)=a
assignment : a=d/dt
assignment : d=3
assignment : dt=4
Community
  • 1
  • 1
Bart Kiers
  • 166,582
  • 36
  • 299
  • 288
  • @dasblinkenlight, you already recommended it, so the OP is aware of it: you don't need to convince me. Since the OP specifically asked if the grammar could remain the same, I posted this. – Bart Kiers Jan 10 '12 at 12:39
  • You are right, I missed the part about "thousands of lines of working code" on the first reading. – Sergey Kalinichenko Jan 10 '12 at 15:53
  • @dasblinkenlight, I didn't mean for you to remove your answer though! Although the OP wanted to change his/her grammar as little as possible, you raise a valid point worthy of an answer. – Bart Kiers Jan 10 '12 at 15:56
  • Bart: nice solution! It requires no changes to my grammer and does exactly what I want! I do find dasblinkenlight's solution to be cleaner, but it would require more work before it can fit in to my project. – Jason Jan 10 '12 at 19:38
4

Although this is not what you are trying to do considering the large amount of working code that you have in the project, you should still consider separating your parser and lexer more thoroughly. I is best to let the parser and the lexer do what they do best, rather than "fusing" them together. The most obvious indication of something being wrong is the lack of symmetry between your ( and ) tokens: one is part of a composite token, while the other one is a stand-alone token.

If refactoring is at all an option, you could change the parser and lexer like this:

grammar diffeq_grammar;

program :   (statement? NEWLINE)* EOF; // <-- You forgot EOF

statement
    :   diffeq
    |   assignment;

diffeq  :   D OVER DT OPEN id CLOSE EQ id; // <-- here, id is a parser rule

assignment
    :   id EQ NUMBER
    |   id EQ id OVER id
    ;

id  : ID | D | DT; // <-- Nice trick, isn't it?

D       : 'D';
DT      : 'DT';
OVER    : '/';
EQ      : '=';
OPEN    : '(';
CLOSE   : ')';
ID      : 'a'..'z'+;
NUMBER  : '0'..'9'+;
NEWLINE : '\r\n'|'\r'|'\n';

You may need to enable backtracking and memoization for this to work (but try compiling it without backtracking first).

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • Why is it a bad practice to have the open parenthesis be part of a larger token and the closed parenthesis be its own token? BTW, I like the id trick. – Jason Jan 10 '12 at 17:58
  • I like this solution, it's clean. This could drop right in to my code if the "id" rule could return an AST node with type "ID" (notice the uppercase) and text value equal to the matched text. Maybe that's possible with: id : ID | D | DT -> ID[$text]; – Jason Jan 10 '12 at 18:02
  • 2
    @Jason In general, grammars for languages with paired symmetric punctuation marks (e.g. `()`, `{}`, `[]`, `«»` etc.) are expect to reflect that symmetry in their structure. Lumping `(` with the `d/dt(` breaks this symmetry, sending the reader in search of the "unbalanced" closing parenthesis. Since grammar files communicate your intent to the readers and maintainers of your code as much as they communicate your intent to the ANTLR tool, I think it is important to track the structure of your language in the grammar as closely as possible. – Sergey Kalinichenko Jan 10 '12 at 19:10
  • @Jason I am not familiar with the new rewrite syntax `->`, so I am not 100% certain that what you are attempting is going to work. But it is certainly worth a try. – Sergey Kalinichenko Jan 10 '12 at 19:15
  • 1
    thanks for the explanation, that makes good sense to me. I really like this solution, but it would take some more work before I can integrate it to my project, so it isn't the solution I will use. – Jason Jan 10 '12 at 19:40
1

Here's the solution I finally used. I know it violates one of my requirements: to keep lexer rules in the lexer and parser rules in the parser, but as it turns out moving DDT to ddt required no change in my code. Also, dasblinkenlight makes some good points about mismatched parenthesis in his answer and comments.

grammar ddt_problem;

program :   (statement? NEWLINE)*;

statement
    :   diffeq
    |   assignment;

diffeq  :   ddt ID ')' '=' ID;

assignment
    :   ID '=' NUMBER
    |   ID '=' ID '/' ID
    ;

ddt :   ( d=ID ) { $d.getText().equals("d") }? '/' ( dt=ID ) { $dt.getText().equals("dt") }? '(';
ID  :   'a'..'z'+;
NUMBER  :   '0'..'9'+;
NEWLINE :   '\r\n'|'\r'|'\n';
Jason
  • 11,709
  • 9
  • 66
  • 82