Trouble Adding ANTLR to Classpath in Java: "package org.antlr.v4.runtime.tree does not exist"

421 Views Asked by At

I'm having difficulties adding ANTLR to my Java classpath and getting it to work. I've followed the usual steps, but I'm still encountering the error message:

package org.antlr.v4.runtime.tree does not  exist(compiler.err.doesnt.exist) org.antlr.v4.runtime.tree

I've downloaded the ANTLR JAR file (antlr4-4.7.1-complete.jar & antlr-4.13.1-complete.jar) from the official website. (for some reason i downloaded 2)

Here's what I've tried so far;

I've set my classpath using the following command in my terminal:

export CLASSPATH="/Users/ciansullivan/Downloads/antlr4-4.7.1-complete.jar"

I've also added a directory containing the JAR file to my PATH.

(I can confirm that when I echo the CLASSPATH, it returns the correct path to the file.)

However, I'm still getting the error. I suspect that the issue might be related to having multiple versions of ANTLR, as I have two installed on my system. I've tried adding each version separately to the classpath, but the problem persists.

Could someone please guide me on how to correctly set up ANTLR in my Java project and resolve this error? Any help would be greatly appreciated.

Additional Information:

Operating System: [Mac OS]

ANTLR Version(s): [antlr4-4.7.1-complete.jar & antlr-4.13.1-complete.jar]

IDE: [VS Code]

1

There are 1 best solutions below

0
Bart Kiers On

Stick the following in a shell script:

#!/usr/bin/env sh

ANTLR_JAR="antlr-4.13.1-complete.jar"

if [ ! -f "$ANTLR_JAR" ]
then
    # Download the ANTLR jar if it isn't in the current working directory
    wget "https://www.antlr.org/download/$ANTLR_JAR"
fi

# Create a test grammar
cat << EOF > Test.g4
grammar Test;
parse : ANY* EOF;
ANY : .;
EOF

# Generate the lexer and parser classes
java -jar "$ANTLR_JAR" Test.g4

# Create a driver class
cat << EOF > Main.java
import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.tree.ParseTree;

public class Main {
    public static void main(String[] args) {
        String source = "test";
        TestLexer lexer = new TestLexer(CharStreams.fromString(source));
        TestParser parser = new TestParser(new CommonTokenStream(lexer));
        ParseTree root = parser.parse();
        System.out.println(root.toStringTree(parser));
    }
}
EOF

# Compile all java source files
javac -cp "$ANTLR_JAR" *.java

# Run the Main class
java -cp .:"$ANTLR_JAR" Main

and run it. It will print:

(parse t e s t <EOF>)