Search code examples
javaantlrantlrworks

Remove (absolute) paths in ANTLR generated java classes:


I am using ANTLRWorks 1.4.3 together with ANTLR 3.4 to generate a Java-based parser and lexer from a grammar file. The generated .java-files contain strings like

C:\\Users\\[path to the eclipse project]\\src\\some\\package\\name\\MyGrammar.g

This absolute path is used as

  • return string e.g. in method getGrammarFileName() of lexer and parser, and
  • throughout the both files various times as comment.

I see following disadvantages:

  • If somebody else with different paths in his development environment will regenerate these files, a lot of changes will be introduced even if no changes in the grammar file were done.
  • Nobody, especially in an open source project, needs to know where I exactly store my grammar files. E.g., what about C:\\Users\\simon\\customerA\\crap_software\\[rest of the path to grammar file]

Is there a way to control this in ANTLRWorks or ANTLR s.th. at least only relative paths are used?


Solution

  • Finally I found a way to solve my own problem.

    Paths seem to depend from where and how you invoke ANTLR. I was not able to achieve this with ANTLRWorks, but using command line ANTLR you are able to perform this. You can do the following (example is for Windows but should be reproducible on other OSes, too):

    1. Download Antlr for command line and copy it to e.g.

      C:\Program Files (x86)\ANTLRworks\antlr-3.4-complete.jar.

    2. Open a Windows command line (cmd.exe) and change to the directory where your grammar file is located:

      cd C:\Users[path to the eclipse project]\src\some\package\name

    3. Invoke

      java -jar "C:\Program Files (x86)\ANTLRworks\antlr-3.4-complete.jar" MyGrammar.g
      

      from commandline.

    The generated java files will only contain the name of your grammar file and no path anymore.