aspose.info
EN

G4 - ANTLR Code File

Updated

What is a G4 file?

The file with .g4 extension contains the grammer for a parser called ANTLR 4. The ANTLR 4 runtime is required to recognize the G4 file. After installation the parsing tool recognize the G4 content as a language which need to be translated in a typical language. Once the parser works it generates the code for the target programming languages such as, Java, C++ or c#. Therefore, it is important to have an ANTLR runtime installed to let the output or generated code work.

G4 file format

G4 file format is relevant to the ANTLR 4 tool which is a programming parser. The G4 file format is designed to keep the grammer for ANTLR which stands for ANother Tool for Language Recognition, is a parser generator. ANTLR takes as input a G4 file which containing a grammar that specifies a language and generates as output source code for a recognizer of that language. The ANTLR 3 supported generating code in the programming languages JavaScript, Ada95, ActionScript, C, C#, Java, Perl, Objective-C, Ruby, Python and Standard ML, the current version only targets Java, JavaScript, C#, C++, Python, Swift, and Go.

Example

Here is a simple example which shows how a grammer is contained in a G4 file. put the following grammar inside file Hello.g4 and save it in a temp directory

// Define a grammar called Hello
grammar Hello;
r  : 'hello' ID ;         // match keyword hello followed by an identifier
ID : [a-z]+ ;             // match lower-case identifiers
WS : [ \t\r\n]+ -> skip ; // skip spaces, tabs, newlines

Then you can run ANTLR like this"

$ cd /tmp
$ antlr4 Hello.g4
$ javac Hello*.java

References

See also