GithubHelp home page GithubHelp logo

antlr4-tools's Introduction

antlr4-tools

Tools to run antlr4 w/o needing to install java or antlr4! The only requirement is Python3, which is typically installed on all developer machines on all operating systems.

Install

$ pip install antlr4-tools

That creates antlr4 and antlr4-parse executables. On Windows, of course, this doesn't just work. You need to add the ...\local-packages\python38\scripts dir to your PATH, which itself might require a fun reboot or perhaps reinstall of the OS. haha.

Windows-specific issues

On Windows, the pip command doesn't just work---you need to add the ...\local-packages\python38\scripts dir to your PATH, which itself might require a fun reboot. If you use WSL on Windows, then the pip install will also properly at the scripts directly (if you run from bash shell).

  1. Go to the Microsoft Store
  2. Search in Microsoft Store for Python
  3. Select the newest version of Python (3.10).
  4. Click the "Get" button. Store installs python and pip at "c:\Users...\AppData\Local\Microsoft\WindowsApps\python.exe" and "c:\Users...\AppData\Local\Microsoft\WindowsApps\pip.exe", respectively. And, it updates the search path immediately with the install.
  5. Open a "cmd" terminal.
  6. You can now type "python" and "pip", and "pip install antlr4-tools". 7. Unfortunately, it does not add that to the search path.
  7. Update the search path to contain c:\Users...\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p8\LocalCache\local-packages\Python310\Scripts. You may need to install MSYS2, then do a find /c/ -name antlr4.exe 2> /dev/null and enter that path.
  8. Or, you can set up an alias to antlr4.exe on that path.

The good news is that the ANTLR4 Python tool downloads the ANTLR jar in a standard location, and you don't need to do that manually. It's also possible to go in a browser, go to python.org, and download the python package. But, it's likely you will need to update the path for antlr4.exe as before.

First run will install Java and ANTLR

If needed, antlr4 will download and install Java 11 and the latest ANTLR jar:

$ antlr4 
Downloading antlr4-4.11.1-complete.jar
ANTLR tool needs Java to run; install Java JRE 11 yes/no (default yes)? y
Installed Java in /Users/parrt/.jre/jdk-11.0.15+10-jre; remove that dir to uninstall
ANTLR Parser Generator  Version 4.11.1
 -o ___              specify output directory where all output is generated
 -lib ___            specify location of grammars, tokens files
...

To override the version of ANTLR jar used, you can pass a -v <version> argument or set ANTLR4_TOOLS_ANTLR_VERSION environment variable:

$ antlr4 -v 4.9.3
ANTLR Parser Generator  Version 4.9.3
 -o ___              specify output directory where all output is generated
 -lib ___            specify location of grammars, tokens files
...
$ ANTLR4_TOOLS_ANTLR_VERSION=4.10.1 antlr4
ANTLR Parser Generator  Version 4.10.1
 -o ___              specify output directory where all output is generated
 -lib ___            specify location of grammars, tokens files
...

Running ANTLR tool on grammars

The antlr4 command forwards all arguments (besides -v mentioned above) to the actual ANTLR tool command:

$ antlr4 JSON.g4 
$ ls JSON*.java
JSONBaseListener.java  JSONLexer.java         JSONListener.java      JSONParser.java
$ antlr4 -Dlanguage=Python3 -visitor JSON.g4
$ ls JSON*.py
JSONLexer.py     JSONListener.py  JSONParser.py    JSONVisitor.py

Parsing using interpreter

The antlr4-parse command requires ANTLR 4.11 and above (but any version of ANTLR works for the plain antlr4 command). It accepts the same -v argument or environment variable to override the ANTLR jar version used. (Note: ^D means control-D and indicates "end of input" on Unix but use ^Z on Windows.)

Let's play with a simple grammar:

grammar Expr;
prog:	expr EOF ;
expr:	expr ('*'|'/') expr
    |	expr ('+'|'-') expr
    |	INT
    |	'(' expr ')'
    ;
NEWLINE : [\r\n]+ -> skip;
INT     : [0-9]+ ;

To parse and get the parse tree in text form, use:

$ antlr4-parse Expr.g4 prog -tree
10+20*30
^D
(prog:1 (expr:2 (expr:3 10) + (expr:1 (expr:3 20) * (expr:3 30))) <EOF>)

Here's how to get the tokens and trace through the parse:

$ antlr4-parse Expr.g4 prog -tokens -trace
10+20*30
[@0,0:1='10',<INT>,1:0]
[@1,2:2='+',<'+'>,1:2]
[@2,3:4='20',<INT>,1:3]
[@3,5:5='*',<'*'>,1:5]
[@4,6:7='30',<INT>,1:6]
[@5,9:8='<EOF>',<EOF>,2:0]
enter   prog, LT(1)=10
enter   expr, LT(1)=10
consume [@0,0:1='10',<8>,1:0] rule expr
enter   expr, LT(1)=+
consume [@1,2:2='+',<3>,1:2] rule expr
enter   expr, LT(1)=20
consume [@2,3:4='20',<8>,1:3] rule expr
enter   expr, LT(1)=*
consume [@3,5:5='*',<1>,1:5] rule expr
enter   expr, LT(1)=30
consume [@4,6:7='30',<8>,1:6] rule expr
exit    expr, LT(1)=<EOF>
exit    expr, LT(1)=<EOF>
exit    expr, LT(1)=<EOF>
consume [@5,9:8='<EOF>',<-1>,2:0] rule prog
exit    prog, LT(1)=<EOF>

Here's how to get a visual tree view:

$ antlr4-parse Expr.g4 prog -gui
10+20*30

The following will pop up in a Java-based GUI window:

On real grammars, it can be useful to get decision-making profiling info:

$ antlr4-parse JavaLexer.g4 JavaParser.g4 compilationUnit -profile dump.csv T.java
$ open /tmp/dump.csv 
$ head -5 /tmp/dump.csv 
Rule,Invocations,Time (ms),Total k,Max k,Ambiguities,DFA cache miss
compilationUnit:0,1,0.164791,1,1,0,1
compilationUnit:1,42,1.106583,42,1,0,2
compilationUnit:2,2,1.73675,2,1,0,2
compilationUnit:3,1,3.969,1,1,0,1

antlr4-tools's People

Contributors

herrcai0907 avatar jcmuel avatar kleinesfilmroellchen avatar parrt avatar vlaci avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

antlr4-tools's Issues

Support for lexer grammar

I'm currently using org.antlr.v4.gui.TestRig for ANTLR teaching to help students debug simple grammars. Since my course uses Python, I'd rather avoid exposing students to Java stuff.

antlr4-parse looks very much like what I'm looking for, but doesn't seem to work for lexer grammars:

With TestRig, I can do:

$ cat Tokens.g4
lexer grammar Tokens;

HELLO : 'hello' ;         // beware the single quotes
ID : [a-z]+ ;             // match lower-case identifiers
INT : [0-9]+ ;
KEYWORD : 'begin' | 'end' | 'for' ; // perhaps this should be elsewhere
WS : [ \t\r\n]+ -> skip ; // skip spaces, tabs, newlines
$ antlr4 Tokens.g4 && javac *.java
$ echo hello | java org.antlr.v4.gui.TestRig Tokens tokens -tokens
[@0,0:4='hello',<'hello'>,1:0]
[@1,6:5='<EOF>',<EOF>,2:0]

However, it crashes when I try antlr4-parse:

$ antlr4-parse Tokens.g4 tokens -tokens 
Exception in thread "main" java.lang.ClassCastException: class org.antlr.v4.gui.Interpreter$IgnoreTokenVocabGrammar cannot be cast to class org.antlr.v4.tool.LexerGrammar (org.antlr.v4.gui.Interpreter$IgnoreTokenVocabGrammar and org.antlr.v4.tool.LexerGrammar are in unnamed module of loader 'app')
        at org.antlr.v4.semantics.SymbolChecks.checkForModeConflicts(SymbolChecks.java:313)
        at org.antlr.v4.semantics.SemanticPipeline.process(SemanticPipeline.java:110)
        at org.antlr.v4.Tool.processNonCombinedGrammar(Tool.java:371)
        at org.antlr.v4.Tool.process(Tool.java:359)
        at org.antlr.v4.tool.Grammar.<init>(Grammar.java:364)
        at org.antlr.v4.gui.Interpreter$IgnoreTokenVocabGrammar.<init>(Interpreter.java:42)
        at org.antlr.v4.gui.Interpreter.interp(Interpreter.java:141)
        at org.antlr.v4.gui.Interpreter.main(Interpreter.java:277)

Timeout due to https://search.maven.org/ being unreachable

with urlopen(f"https://search.maven.org/solrsearch/select?q=a:antlr4-master+g:org.antlr",
timeout=10) as response:

Facing timeout at L26 antlr4_tool_runner.py since https://search.maven.org/ users are now redirected to https://central.sonatype.com/
Reference:
https://central.sonatype.org/faq/what-happened-to-search-maven-org/#what-about-the-searchmavenorg-api

The link used in antlr4_tool_runner.py: https://search.maven.org/solrsearch/select?q=a:antlr4-master+g:org.antlr is unreachable.

Windows. ANTLR tools compiled to JRE 11 (class file 55), but installed JRE only recognizes up to JRE 8 (class file 52).

Hi,

I'm doing this both in Linux and Windows, and it's working fine in Linux but not in Windows:

  • Running python -m pip install --upgrade pip antlr4-tools, which installs antlr4-tools-0.2.
  • Running echo Y | antlr4, which downloads antlr4-4.13.0-complete.jar and runs OK in Linux but not in Windows.

The error is:

Exception in thread "main" java.lang.UnsupportedClassVersionError: org/antlr/v4/Tool has been compiled by a more recent version of the Java Runtime (class file version 55.0), this version of the Java Runtime only recognizes class file versions up to 52.0

Shouldn't ANTLR tools be installing an adequate version of JRE?

Is there any easy way to fix this?

Many thanks!

When to publish v0.2 to PyPI release ?

I've seen that you updated a try-catch clause for get_latest_version function, and updated it on Version 0.2

But I can't find the release on PyPI, it's still v0.1.

And I also noticed that the Github Release may be something missed up. The latest version you released 5 days ago was actually v0.2 but you still tagged it as v0.1 @parrt

Error: A JNI error has occurred, please check your installation and try again

I downloaded this repo and run python setup.py install. python is 3.10.8

then, I run antlr4, got the following errors

antlr4-tools % antlr4
Error: A JNI error has occurred, please check your installation and try again
Exception in thread "main" java.lang.UnsupportedClassVersionError: JVMCFRE003 bad major version; class=org/antlr/v4/Tool, offset=6
	at java.lang.ClassLoader.defineClassImpl(Native Method)
	at java.lang.ClassLoader.defineClassInternal(ClassLoader.java:398)
	at java.lang.ClassLoader.defineClass(ClassLoader.java:359)
	at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
	at java.net.URLClassLoader.defineClass(URLClassLoader.java:682)
	at java.net.URLClassLoader.access$400(URLClassLoader.java:89)
	at java.net.URLClassLoader$ClassFinder.run(URLClassLoader.java:1086)
	at java.security.AccessController.doPrivileged(AccessController.java:774)
	at java.net.URLClassLoader.findClass(URLClassLoader.java:589)
	at java.lang.ClassLoader.loadClassHelper(ClassLoader.java:953)
	at java.lang.ClassLoader.loadClass(ClassLoader.java:898)
	at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:352)
	at java.lang.ClassLoader.loadClass(ClassLoader.java:881)
	at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:601)

My java version

% java -version
openjdk version "1.8.0_282"
OpenJDK Runtime Environment (build 1.8.0_282-b08)

Any idea why? thanks

antlr4 isn't robust with slow links.

I've noticed this on my machines and now over in github actions build for grammars-v4. When the link is bad, the antlr4 tool fails.

Traceback (most recent call last):
  File "/opt/hostedtoolcache/Python/3.10.11/x64/lib/python3.10/site-packages/antlr4_tool_runner.py", line 26, in latest_version
    with urlopen(f"https://search.maven.org/solrsearch/select?q=a:antlr4-master+g:org.antlr") as response:
  File "/opt/hostedtoolcache/Python/3.10.11/x64/lib/python3.10/urllib/request.py", line 216, in urlopen
    return opener.open(url, data, timeout)
  File "/opt/hostedtoolcache/Python/3.10.11/x64/lib/python3.10/urllib/request.py", line 525, in open
    response = meth(req, response)
  File "/opt/hostedtoolcache/Python/3.10.11/x64/lib/python3.10/urllib/request.py", line 634, in http_response
    response = self.parent.error(
  File "/opt/hostedtoolcache/Python/3.10.11/x64/lib/python3.10/urllib/request.py", line 563, in error
    return self._call_chain(*args)
  File "/opt/hostedtoolcache/Python/3.10.11/x64/lib/python3.10/urllib/request.py", line 496, in _call_chain
    result = func(*args)
  File "/opt/hostedtoolcache/Python/3.10.11/x64/lib/python3.10/urllib/request.py", line 643, in http_error_default
    raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 504: Gateway Time-out

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/opt/hostedtoolcache/Python/3.10.11/x64/bin/antlr4", line 8, in <module>
    sys.exit(tool())
  File "/opt/hostedtoolcache/Python/3.10.11/x64/lib/python3.10/site-packages/antlr4_tool_runner.py", line 131, in tool
    args, version = get_version_arg(args)
  File "/opt/hostedtoolcache/Python/3.10.11/x64/lib/python3.10/site-packages/antlr4_tool_runner.py", line 123, in get_version_arg
    version = latest_version()
  File "/opt/hostedtoolcache/Python/3.10.11/x64/lib/python3.10/site-packages/antlr4_tool_runner.py", line 36, in latest_version
    version_dirs = list(filter(lambda directory: re.match(r"[0-9]+\.[0-9]+\.[0-9]+", directory), os.listdir(mvn_repo)))
FileNotFoundError: [Errno 2] No such file or directory: '/home/runner/.m2/repository/org/antlr/antlr4'
Could not get latest version number, attempting to fall back to latest downloaded version...
Build failed
Build completed, time: 00:01:02.4911135
./fortran/fortran90 failed
finished in 00:01:02.5069344
Write-Error: /home/runner/work/grammars-v4/grammars-v4/_scripts/test.ps1:384
Line |
 384 |      Test-AllGrammars -Target $target -PreviousCommit $pc -CurrentComm …
     |      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     | Failed grammars: ./fortran/fortran90

This is happening because it is trying to get the latest version of the Antlr tool.

with urlopen(f"https://search.maven.org/solrsearch/select?q=a:antlr4-master+g:org.antlr") as response:

I can program around this by looking at the output of the tool and grep'ing for some string that says the link is bad. But, the better way would be to loop over the call (maybe 5 times) and catching link errors.

The version of the java executable should actually be checked

  • This code "tests" the version of java, but it's false, so it never gets checked.
  • Over here in Antlr4BuildTasks, I don't check the version of java, but I need to because some versions of java don't work, e.g., version 7. Even a quick "java --version" would have found that v7 of java doesn't work because there's no "--version" option.
  • The Antlr tool jar has a minimum requirement of version 11 or newer.
  • The "Quick Start" instructions over on antlr.org should stop defining the alias "alias antlr4='java -jar /usr/local/lib/antlr-4.10.1-complete.jar'" and just point to set up the tools from this repo. The tool here is much better because it could check the version of java, and download a version that can work if one tries to use the wrong version.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.