Remove (absolute) paths in ANTLR generated java classes:

陌路散爱 提交于 2019-12-12 15:20:19

问题


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?


回答1:


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.




回答2:


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

Short answer

No.

Long(er) answer (Containing highly subjective views! Proceed at own risk)

This is target-specific, but, AFAIK, no target allows you to specify the type (absolute or relative) of the path.

The "no" might be because getGrammarFileName() is only used while debugging generated lexers/parsers. And one should probably not check in generated source files into source control, so no one would ever see the path you see in your generated source file. One ought to check in the grammar, and let developers generate their own lexers/parsers from it.

Again, this is all speculation on my part.



来源:https://stackoverflow.com/questions/12385765/remove-absolute-paths-in-antlr-generated-java-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!