preface

Some time ago, I replaced my M1 Mac laptop, and used antLR when learning relevant knowledge of compilation principle. Antlr is an open source parser generation tool based on Java development, which can generate corresponding parser according to syntax rule files, so Java needs to be installed before installing the tool. The M1 version is installed and used differently.

Installing the Java Environment

As of October 2021, only the ARM version of Oracle’s JDK for macOS is available in Java17, while the X86 version can be installed, but will be translated and run using Rosetta2, resulting in a significant drop in productivity and potential compatibility issues.

Alternatively, you can use Azul Zulu’s Java JDK to solve the problem. They provide basically all Java versions arm versions

Antlr4 officially requires Java version 1.7 or higher, so you can choose your own version to install.

After downloading, click Install and enter it on the command linejava -versionYou can view the installed version number, as shown in the figure below

Install antlr4

Open the official website to see how to installOn the M1 Mac, the antLR4 tool can be installed by executing the corresponding commands in sequence

Note that alias provides aliases for commands, but only in the current command line window. Closing or creating a new window requires a new alias, which can be written into the shell interpreter’s configuration file so that each new window takes effect by default

## ZSH modifs the.zshrc script and bash modifs the.bashrc script
vim ~/.zshrc

#Add the following two lines at the end of the textAlias antlr4=' Java -jar /usr/local/lib/antlr-4.9.2-complete.jar' alias grun=' Java org.antlr.v4.gui.testrig 'Copy the code

Generate a parser with Antlr

Create a folder with the following directory structure

| - grammmars | | - SRC | | -- PlayScript. G4 | | -- CommonLexer. G4Copy the code

Antlr generates the compiler by parsing the rule file. Rules files end in. G4. Lexical rules and grammatical rules can be placed in the same file. We split it up, commonlexer.g4 for lexical rules and playscript.g4 for grammatical rules. Making the address

Go to the SRC directory and type the commands in turn to generate a parser

antlr4 PlayScript.g4 -o ./antlrtest
javac antlrtest/*.java
Copy the code

Then test the generated parser by running the following command

grun antlrtest.PlayScript expression -gui
Copy the code

Test PlayScript’s expression method, which parses expressions, and display the results in a graphical interface.

Next, type in the console

age + 10 * 2 + 10
Copy the code

Then press^ + DThe parser then parses the syntax and pops up a window showing the ASTNow that you have the parse tree, you can focus on writing the grammar rules

The resources

www.winsonlo.com/it/howto/zu…