### ANTLR Grammar Start Rule and Input Example Source: https://github.com/antlr/antlr4/blob/dev/runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/JavaExpressions_7.txt Demonstrates the starting rule 's' for the grammar and provides a sample input string '(T)x' to be parsed. The output shows the resulting parse tree. ```text [start] s [input] (T)x [output] """ (s (e ( (typespec T) ) (e x)) ) """ ``` -------------------------------- ### Install License and Readme Files Source: https://github.com/antlr/antlr4/blob/dev/runtime/Cpp/CMakeLists.txt Installs the LICENSE.txt and README.md files to the documentation directory. The LICENSE.txt file is installed if it exists in the current or parent directory. ```cmake if(EXISTS LICENSE.txt) install(FILES LICENSE.txt DESTINATION ${CMAKE_INSTALL_DOCDIR}) elseif(EXISTS ../../LICENSE.txt) install(FILES ../../LICENSE.txt DESTINATION ${CMAKE_INSTALL_DOCDIR}) endif() install(FILES README.md VERSION DESTINATION ${CMAKE_INSTALL_DOCDIR}) ``` -------------------------------- ### Clone and Setup PHP Runtime Source: https://github.com/antlr/antlr4/blob/dev/doc/creating-a-language-target.md Clone the PHP runtime repository and install its dependencies using Composer. This is necessary for debugging the PHP target, as it's hosted separately. ```bash git clone -b dev https://github.com/antlr/antlr-php-runtime.git runtime/PHP cd runtime/PHP composer install ``` -------------------------------- ### ANTLR Tool Download and Setup Source: https://github.com/antlr/antlr4/blob/dev/doc/getting-started.md When running the antlr4 command for the first time, it may prompt to download the ANTLR jar and install Java if not already present. This output shows the process. ```bash antlr4 Downloading antlr4-4.13.2-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.13.2 -o ___ specify output directory where all output is generated -lib ___ specify location of grammars, tokens files ... ``` -------------------------------- ### ANTLR Parser Execution Example Source: https://github.com/antlr/antlr4/blob/dev/runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserExec/Basic.txt Shows the start rule, input, and expected output for the ANTLR grammar. ```text [start] a [input] abc 34 [output] """abc34 """ ``` -------------------------------- ### Installing the Executable Source: https://github.com/antlr/antlr4/blob/dev/runtime/Cpp/demo/CMakeLists.txt Installs the 'antlr4-demo' executable to the 'share' directory as a 'dev' component. ```cmake install(TARGETS antlr4-demo DESTINATION "share" COMPONENT dev ) ``` -------------------------------- ### Example Rule Matching One, Two, or Three Tokens Source: https://github.com/antlr/antlr4/blob/dev/doc/parser-rules.md This rule demonstrates how a start rule can match different amounts of input based on the provided tokens. It does not enforce consumption of all input. ```antlr s : ID | ID '+' | ID '+' INT ; ``` -------------------------------- ### Download ANTLR Book Examples Source: https://github.com/antlr/antlr4/blob/dev/doc/java-target.md Download and extract the ANTLR v4 book examples, specifically the ArrayInit.g4 grammar, from the provided URL. ```bash pushd ~/Downloads wget http://media.pragprog.com/titles/tpantlr2/code/tpantlr2-code.tgz tar xvfz tpantlr2-code.tgz popd ``` -------------------------------- ### Parser Start Rule and Input Source: https://github.com/antlr/antlr4/blob/dev/runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/DirectCallToLeftRecursiveRule_3.txt Specifies the starting rule for the parser as 'a' and provides the input string 'x y z' for parsing. This setup is used to test the behavior of the left-recursive grammar with a sample input. ```text a x y z ``` -------------------------------- ### Example Output Source: https://github.com/antlr/antlr4/blob/dev/doc/go-target.md This is the expected output when running the complete ANTLR Go runtime example with the provided input. ```text {"a":1} {"a":1} "a":1 1 ``` -------------------------------- ### ANTLR Grammar Start Rule and Input Source: https://github.com/antlr/antlr4/blob/dev/runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/Declarations_1.txt Specifies the starting rule for the ANTLR grammar and provides sample input for parsing. This setup is used to test the grammar's ability to correctly parse a simple identifier. ```antlr [start] s [input] a ``` -------------------------------- ### Install ANTLR and Runtime Tests Source: https://github.com/antlr/antlr4/blob/dev/doc/creating-a-language-target.md Run these commands to install the necessary ANTLR and runtime test JARs before executing trace scripts. This ensures the correct dependencies are available. ```bash cd ANTLR-ROOT-DIR mvn install -DskipTests=true cd runtime-tests mvn install -DskipTests=true # yes do it again ``` -------------------------------- ### Example Command Line Execution Source: https://github.com/antlr/antlr4/blob/dev/doc/go-target.md This shows how to run the Go program, passing the input file as a command-line argument. ```shell go run test.go input ``` -------------------------------- ### Check and Install Environment Dependencies Source: https://github.com/antlr/antlr4/blob/dev/doc/building-antlr.md Verify that Java (OpenJDK 11 JRE) and Maven are installed on your system. If not, this command will install them on Ubuntu. ```bash sudo apt-get update # Get Java java > /dev/null 2>&1 if [[ "$?" != "0" ]]; then sudo apt install -y openjdk-11-jre-headless; fi # Get Mvn mvn > /dev/null 2>&1 if [[ "$?" != "0" ]]; then sudo apt install -y maven; fi ``` -------------------------------- ### Start Rule and Input Source: https://github.com/antlr/antlr4/blob/dev/runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/CompositeParsers/ImportedGrammarWithEmptyOptions.txt Specifies the starting rule for the parser and provides a sample input string to test the grammar. ```text s b ``` -------------------------------- ### Install ANTLR4 Go Target Source: https://github.com/antlr/antlr4/blob/dev/README.md Use this command to get the ANTLR4 Go target for use with `go get` and `import`. Note that runtime development is still in the main ANTLR4 repository. ```bash $ go get github.com/antlr4-go/antlr ``` -------------------------------- ### Input and Output Example Source: https://github.com/antlr/antlr4/blob/dev/runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/JavaExpressions_10.txt Demonstrates parsing a sample input string representing a Java expression and its corresponding parse tree output. ```text [start] s [input] a.f(x)==T.c [output] """(s (e (e (e (e a) . f) ( (expressionList (e x)) )) == (e (e T) . c)) ) """ ``` -------------------------------- ### Input and Output Example Source: https://github.com/antlr/antlr4/blob/dev/runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/JavaExpressions_2.txt Demonstrates the parsing of a sample Java expression '(a|b)&c' and its corresponding abstract syntax tree output. ```text [input] (a|b)&c [output] """(s (e (e ( (e (e a) | (e b)) )) & (e c)) ) """ ``` -------------------------------- ### Start Rule and Input Source: https://github.com/antlr/antlr4/blob/dev/runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/CompositeParsers/DelegatorRuleOverridesDelegate.txt Specifies 'a' as the start rule for the parser and provides 'c' as the input string to be parsed. ```text [start] a [input] c ``` -------------------------------- ### Install Static Library Source: https://github.com/antlr/antlr4/blob/dev/runtime/Cpp/runtime/CMakeLists.txt Installs the ANTLR4 static library to the appropriate runtime directories. ```cmake if (TARGET antlr4_static) install(TARGETS antlr4_static EXPORT antlr4-targets ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}) endif() ``` -------------------------------- ### Lexer Input and Output Example Source: https://github.com/antlr/antlr4/blob/dev/runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LexerExec/Slashes.txt Demonstrates the input string '\ / \/ /\' and the corresponding lexer output, showing token recognition and positions. ```text \ / \/ /\ [@0,0:0='\',<1>,1:0] [@1,2:2='/',<2>,1:2] [@2,4:5='\/',<3>,1:4] [@3,7:8='/\',<4>,1:7] [@4,9:8='',<-1>,1:9] ``` -------------------------------- ### Get Help for boot.py Script Source: https://github.com/antlr/antlr4/blob/dev/doc/swift-target.md Run the boot.py script with the --help flag to get information about its usage and available options for managing ANTLR Swift runtime integration. ```bash python boot.py --help ``` -------------------------------- ### ANTLR Grammar Execution Example Source: https://github.com/antlr/antlr4/blob/dev/runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/Sets/UnicodeUnescapedBMPRangeSet.txt Specifies the starting rule for the ANTLR parser and provides the input string 'aáäáâåd' to test the grammar. The expected output is the input string itself, demonstrating that the unescaped Unicode range correctly matches the characters. ```text [start] a [input] aáäáâåd [output] """aáäáâåd """ ``` -------------------------------- ### ANTLR Start Rule and Input Source: https://github.com/antlr/antlr4/blob/dev/runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/PrefixOpWithActionAndLabel_3.txt Specifies the starting rule for the grammar and provides sample input for parsing. ```text [start] s [input] a=b+c ``` -------------------------------- ### Lexer Input and Output Example Source: https://github.com/antlr/antlr4/blob/dev/runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LexerExec/EscapedCharacters.txt Shows the input string 'x\n' and its corresponding lexer output, demonstrating how the 'X' and 'LF' rules are recognized. ```text Input: """x """ Output: [@0,0:0='x',<2>,1:0] [@1,1:1='\n',<1>,1:1] [@2,2:1='',<-1>,2:0] ``` -------------------------------- ### Input and Output Example Source: https://github.com/antlr/antlr4/blob/dev/runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/JavaExpressions_6.txt Demonstrates parsing of a simple expression 'a^b^c' using the defined grammar, showing the resulting parse tree. ```text [input] a^b^c [output] """(s (e (e a) ^ (e (e b) ^ (e c))) ) """ ``` -------------------------------- ### ANTLR Grammar Execution Example Source: https://github.com/antlr/antlr4/blob/dev/runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/Sets/LexerStarSet.txt Demonstrates the execution of the ANTLR grammar with a specific input. The grammar is set to start with rule 'a', and the input 'abaac' is provided. The expected output shows the input string itself, as captured by the `` action. ```text [type] Parser [grammar] grammar T; a : A {} ; A : ('a'|'b')* 'c' ; [start] a [input] abaac [output] """abaac """ ``` -------------------------------- ### Install GPG and Generate Key Source: https://github.com/antlr/antlr4/wiki/Deploying-ANTLR-mvn-artifacts Install GPG using Homebrew and generate a new PGP key if one does not exist. This is a prerequisite for signing artifacts. ```bash $ brew install gpg $ gpg --gen-key # if you have not set this up ``` -------------------------------- ### Input and Output Example Source: https://github.com/antlr/antlr4/blob/dev/runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/JavaExpressions_1.txt Demonstrates parsing of a simple expression with bitwise AND and OR operators. ```text [input] a|b&c [output] """(s (e (e a) | (e (e b) & (e c))) ) """ ``` -------------------------------- ### Lexer Input and Output Example Source: https://github.com/antlr/antlr4/blob/dev/runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LexerErrors/DFAToATNThatMatchesThenFailsInATN.txt Provides the input string 'ababcx' and the expected lexer output, including token recognition and EOF. This example highlights the context for the lexer error. ```text ababcx ``` ```text [@0,0:1='ab',<1>,1:0] [@1,2:4='abc',<2>,1:2] [@2,6:5='',<-1>,1:6] ``` -------------------------------- ### Install Shared Library Source: https://github.com/antlr/antlr4/blob/dev/runtime/Cpp/runtime/CMakeLists.txt Installs the ANTLR4 shared library to the appropriate runtime directories. ```cmake if (TARGET antlr4_shared) install(TARGETS antlr4_shared EXPORT antlr4-targets ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}) endif() ``` -------------------------------- ### Start Rule and Input Source: https://github.com/antlr/antlr4/blob/dev/runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/CompositeParsers/DelegatorInvokesDelegateRuleWithReturnStruct.txt Specifies the starting rule for the parser and the input string to be processed. ```text [start] s [input] b ``` -------------------------------- ### Start Rule and Input Source: https://github.com/antlr/antlr4/blob/dev/runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserExec/LL1OptionalBlock_1.txt Specifies the starting rule for the grammar and provides an empty input, which will result in the optional block not being matched. ```text [start] a [input] [output] """ ``` -------------------------------- ### Full ANTLR4 Integration Example Source: https://github.com/antlr/antlr4/blob/dev/runtime/Cpp/cmake/Antlr4Package.md This comprehensive example demonstrates finding both the ANTLR4 runtime and generator packages, setting the ANTLR JAR location, generating lexer and parser code, including necessary directories, and linking the executable against the ANTLR4 shared library. ```cmake # Bring in the required packages find_package(antlr4-runtime REQUIRED) find_package(antlr4-generator REQUIRED) # Set path to generator set(ANTLR4_JAR_LOCATION ${PROJECT_SOURCE_DIR}/thirdparty/antlr/antlr-4.13.2-complete.jar) # generate lexer antlr4_generate( antlrcpptest_lexer ${CMAKE_CURRENT_SOURCE_DIR}/TLexer.g4 LEXER FALSE FALSE "antlrcpptest" ) # generate parser antlr4_generate( antlrcpptest_parser ${CMAKE_CURRENT_SOURCE_DIR}/TParser.g4 PARSER FALSE TRUE "antlrcpptest" "${ANTLR4_TOKEN_FILES_antlrcpptest_lexer}" "${ANTLR4_TOKEN_DIRECTORY_antlrcpptest_lexer}" ) # add directories for generated include files include_directories( ${PROJECT_BINARY_DIR} ${ANTLR4_INCLUDE_DIR} ${ANTLR4_INCLUDE_DIR_antlrcpptest_lexer} ${ANTLR4_INCLUDE_DIR_antlrcpptest_parser} ) # add generated source files add_executable( Parsertest main.cpp ${ANTLR4_SRC_FILES_antlrcpptest_lexer} ${ANTLR4_SRC_FILES_antlrcpptest_parser} ) # add required runtime library add_dependencies( Parsertest antlr4_shared ) target_link_libraries( Parsertest PRIVATE antlr4_shared) ``` -------------------------------- ### Example JSON Input File Source: https://github.com/antlr/antlr4/blob/dev/doc/dart-target.md A sample JSON file used as input for the Dart parsing example. ```json {"a":1} ``` -------------------------------- ### Install ANTLR Artifacts Locally Source: https://github.com/antlr/antlr4/wiki/Deploying-ANTLR-mvn-artifacts Use this script to clean, build, and install ANTLR artifacts into the local Maven repository for testing. ```bash $ ./bild.py clean $ ./bild.py mkjar $ ./bild.py mksrc $ ./bild.py mkdoc $ ./bild.py install ``` ```bash $ ./bild.py install ``` -------------------------------- ### Go Module Reference Example Source: https://github.com/antlr/antlr4/blob/dev/doc/go-target.md This is how you import the ANTLR Go runtime package in your Go source files after upgrading to the v4 module path. ```go import "github.com/antlr4-go/antlr/v4" ``` -------------------------------- ### Install Runtime Headers Source: https://github.com/antlr/antlr4/blob/dev/runtime/Cpp/runtime/CMakeLists.txt Installs the ANTLR4 C++ runtime header files to the specified include directory for the 'dev' component. ```cmake install(DIRECTORY "${PROJECT_SOURCE_DIR}/runtime/src/" DESTINATION "${libantlrcpp_INCLUDE_INSTALL_DIR}" COMPONENT dev FILES_MATCHING PATTERN "*.h" ) ``` -------------------------------- ### Run Dart JSON Parser Example Source: https://github.com/antlr/antlr4/blob/dev/doc/dart-target.md Command to execute the Dart main function, passing the example JSON file as an argument to parse. ```shell dart bin/main.dart example.json ``` -------------------------------- ### AmbigLR_5 Example Input Source: https://github.com/antlr/antlr4/blob/dev/runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/AmbigLR_5.txt Provides a sample input string to be parsed by the AmbigLR_5 grammar. ```text """ (1+2)*3 """ ``` -------------------------------- ### Case-Insensitive Lexer Input Example Source: https://github.com/antlr/antlr4/blob/dev/doc/options.md This example shows various inputs that would be matched by a case-insensitive lexer, demonstrating the effect of the `caseInsensitive` option. ```text abcXYZ äéöüßÄÉÖÜß àâæçÙÛÜŸ ćčđĐŠŽ àèéÌÒÙ áéÚÜ¡¿ αβγΧΨΩ абвЭЮЯ ``` -------------------------------- ### ANTLR Grammar Execution Example Source: https://github.com/antlr/antlr4/blob/dev/doc/grammars.md Demonstrates the command-line execution of an ANTLR-generated grammar ('Count.g4') using 'grun' and shows the expected output. ```bash $ cd foo $ antlr4 Count.g4 # generates code in the current directory (foo) $ ls Count.g4 CountLexer.java CountParser.java Count.tokens CountLexer.tokens CountBaseListener.java CountListener.java $ javac *.java $ cd .. $ grun foo.Count list => 9, 10, 11 => EOF <= 3 ints ``` -------------------------------- ### Character Set Examples Source: https://github.com/antlr/antlr4/blob/dev/doc/lexer-rules.md Demonstrates the use of character sets for matching whitespace, identifiers, and special characters. ```ANTLR WS : [ ] -> skip ; UNICODE_WS : [\p{White_Space}] -> skip; ID : [a-zA-Z] [a-zA-Z0-9]* ; UNICODE_ID : [\p{Alpha}\p{General_Category=Other_Letter}] [\p{Alnum}\p{General_Category=Other_Letter}]* ; EMOJI : [\u{1F4A9}\u{1F926}] ; DASHBRACK : [\-\ ]+ ; DASH : [---] ; ``` -------------------------------- ### Input and Output Example Source: https://github.com/antlr/antlr4/blob/dev/runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/JavaExpressions_8.txt Demonstrates parsing a specific input string 'new A().b' using the defined grammar and shows the resulting parse tree output. ```text [input] new A().b [output] """(s (e (e new (typespec A) ( )) . b) ) """ ``` -------------------------------- ### Input and Output Example Source: https://github.com/antlr/antlr4/blob/dev/runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/JavaExpressions_9.txt Demonstrates parsing a specific Java expression input and its corresponding parse tree output. This example shows how a parenthesized type cast followed by a member access and method call is parsed. ```input (T)t.f() ``` ```output "(s (e (e ( (typespec T) ) (e (e t) . f)) ( )) ) " ``` -------------------------------- ### Install ANTLR Artifacts to Local Maven Repository Source: https://github.com/antlr/antlr4/blob/dev/doc/antlr-project-testing.md Installs ANTLR artifacts into the local Maven repository. Ensure MAVEN_OPTS is set for sufficient memory, especially on Linux. ```bash $ export MAVEN_OPTS="-Xmx1G" # don't forget this on linux $ mvn install -DskipTests # make sure all artifacts are visible on this machine ``` -------------------------------- ### Fortran 90 Comment Example Source: https://github.com/antlr/antlr4/blob/dev/doc/target-agnostic-grammars.md Illustrates Fortran 90 syntax where lines starting with 'c' in column 1 are comments, and deviations are syntax errors. ```fortran c Hello World. c This is a syntax error because 'c' does not start in column 1 program hello print *, 'Hello World!' end ``` -------------------------------- ### Lexer Input and Output Example Source: https://github.com/antlr/antlr4/blob/dev/runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LexerExec/CharSetWithMissingEscapeChar.txt Provides the input string '34 ' for the lexer and shows the expected output, including the token stream generated by ANTLR. ```text Input: """34 """ Output: I [@0,0:1='34',<1>,1:0] [@1,3:2='',<-1>,1:3] ``` -------------------------------- ### ANTLR Input and Output Example Source: https://github.com/antlr/antlr4/blob/dev/runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/Listeners/TokenGetters_2.txt Provides the input string and expected output for the ANTLR grammar, illustrating parse tree structure and token information. ```text Input: abc Output: (a abc) [@0,0:2='abc',<4>,1:0] ``` -------------------------------- ### ANTLR Grammar Execution Example Source: https://github.com/antlr/antlr4/blob/dev/runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/Sets/CharSetLiteral.txt This section shows the ANTLR grammar's start rule, input, and expected output. The input 'A a B b' is processed by the grammar, resulting in the output of each matched character. ```text [start] a [input] A a B b [output] A a B b ``` -------------------------------- ### Lexer Predicate for Start of Line Check Source: https://github.com/antlr/antlr4/blob/dev/doc/predicates.md An example of a lexer rule using a predicate to check the character position within the line. The predicate `this.getCharPositionInLine()==0` ensures this rule only matches at the beginning of a line. ```antlr INDENT : [ \t]+ {System.out.println("INDENT")>} {this.getCharPositionInLine()==0}? ; ``` -------------------------------- ### Basic TypeScript Parser Setup Source: https://github.com/antlr/antlr4/blob/dev/doc/typescript-target.md Initialize a lexer and parser with input text to generate a parse tree. Replace 'your text to parse here' with actual input and consider using FileStream for file inputs. ```typescript import { CharStream, CommonTokenStream } from 'antlr4'; import MyGrammarLexer from './MyGrammarLexer'; import MyGrammarParser from './MyGrammarParser'; const input = "your text to parse here" const chars = new CharStream(input); // replace this with a FileStream as required const lexer = new MyGrammarLexer(chars); const tokens = new CommonTokenStream(lexer); const parser = new MyGrammarParser(tokens); const tree = parser.MyStartRule(); ``` -------------------------------- ### ANTLR Start Rule Source: https://github.com/antlr/antlr4/blob/dev/runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserErrors/DuplicatedLeftRecursiveCall_2.txt Specifies the starting rule for the ANTLR parser, which is 'start' in this grammar. ```antlr start ``` -------------------------------- ### Build and Deploy C++ Runtime on macOS Source: https://github.com/antlr/antlr4/blob/dev/doc/releasing-antlr.md Use this script to build the C++ runtime for macOS and prepare it for distribution. Ensure you have Xcode 7+ installed. ```bash cd ~/antlr/code/antlr4/runtime/Cpp rm CMakeCache.txt # otherwise can't find some include files ./deploy-macos.sh cp antlr4-cpp-runtime-macos.zip ~/antlr/sites/website-antlr4/download/antlr4-cpp-runtime-4.13.2-macos.zip ``` -------------------------------- ### Build C# Runtime with MSBuild Source: https://github.com/antlr/antlr4/blob/dev/doc/releasing-antlr.md Builds the C# ANTLR runtime in Release configuration using dotnet build. Ensure msbuild and nuget are installed. ```bash cd ~/antlr/code/antlr4/runtime/CSharp/src dotnet build -c Release Antlr4.csproj ``` -------------------------------- ### Input and Output Example Source: https://github.com/antlr/antlr4/blob/dev/runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/CompositeParsers/DelegatorInvokesDelegateRuleWithArgs.txt Provides the input 'b' and the expected output '"S.a"1000' when the 'M' grammar is used to parse the input, demonstrating the successful invocation and argument passing. ```text b ``` ```text "S.a1000" ``` -------------------------------- ### Setting Install Include Directory for ANTLR C++ Runtime Source: https://github.com/antlr/antlr4/blob/dev/runtime/Cpp/runtime/CMakeLists.txt Defines the installation directory for the ANTLR C++ runtime header files. This ensures that installed libraries can find their headers correctly. ```cmake set(libantlrcpp_INCLUDE_INSTALL_DIR "${CMAKE_INSTALL_INCLUDEDIR}/antlr4-runtime") ``` -------------------------------- ### Complete ANTLR Go Runtime Example Source: https://github.com/antlr/antlr4/blob/dev/doc/go-target.md This Go program demonstrates how to use the generated ANTLR parser and lexer for JSON. It includes a custom listener to print encountered ParseTreeContexts and expects input from the command line. ```go package main import ( "github.com/antlr4-go/antlr/v4" "./parser" // Note that with modules you may not be able to use a relative immport path "os" "fmt" ) type TreeShapeListener struct { *parser.BaseJSONListener } func NewTreeShapeListener() *TreeShapeListener { return new(TreeShapeListener) } func (this *TreeShapeListener) EnterEveryRule(ctx antlr.ParserRuleContext) { fmt.Println(ctx.GetText()) } func main() { input, _ := antlr.NewFileStream(os.Args[1]) lexer := parser.NewJSONLexer(input) stream := antlr.NewCommonTokenStream(lexer,0) p := parser.NewJSONParser(stream) p.AddErrorListener(antlr.NewDiagnosticErrorListener(true)) tree := p.Json() antlr.ParseTreeWalkerDefault.Walk(NewTreeShapeListener(), tree) } ``` -------------------------------- ### Start Rule for the Parser Source: https://github.com/antlr/antlr4/blob/dev/runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/CompositeParsers/ImportedRuleWithAction.txt Specifies the start rule 's' for the composite parser. ```text s ``` -------------------------------- ### Input and Output Example Source: https://github.com/antlr/antlr4/blob/dev/runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LexerExec/HexVsID.txt Provides sample input and the corresponding tokenization output generated by the lexer grammar. This helps visualize how the lexer interprets the input based on the defined rules. ```text Input: x 0 1 a.b a.l Output: [@0,0:0='x',<5>,1:0] [@1,1:1=' ',<6>,1:1] [@2,2:2='0',<2>,1:2] [@3,3:3=' ',<6>,1:3] [@4,4:4='1',<2>,1:4] [@5,5:5=' ',<6>,1:5] [@6,6:6='a',<5>,1:6] [@7,7:7='.',<4>,1:7] [@8,8:8='b',<5>,1:8] [@9,9:9=' ',<6>,1:9] [@10,10:10='a',<5>,1:10] [@11,11:11='.',<4>,1:11] [@12,12:12='l',<5>,1:12] [@13,13:12='',<-1>,1:13] ``` -------------------------------- ### Input and Output Example Source: https://github.com/antlr/antlr4/blob/dev/runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/SemPredEvalLexer/EnumNotID.txt Shows the input string 'enum abc enum' and the resulting tokenization, highlighting how the semantic predicate correctly identifies the 'enum' tokens. ```text enum abc enum [@0,0:3='enum',<1>,1:0] [@1,5:7='abc',<2>,1:5] [@2,9:12='enum',<1>,1:9] [@3,13:12='',<-1>,1:13] s0-' '->:s3=>3 ``` -------------------------------- ### Case-Insensitive Lexer Grammar Example Source: https://github.com/antlr/antlr4/blob/dev/doc/options.md This example demonstrates the `caseInsensitive` grammar option, enabling ANTLR to match tokens regardless of case. It shows a grammar with various language-specific tokens and an example of input that would be matched. ```g4 lexer grammar L; options { caseInsensitive = true; } ENGLISH_TOKEN: [a-z]+; GERMAN_TOKEN: [äéöüß]+; FRENCH_TOKEN: [àâæ-ëîïôœùûüÿ]+; CROATIAN_TOKEN: [ćčđšž]+; ITALIAN_TOKEN: [àèéìòù]+; SPANISH_TOKEN: [áéíñóúü¡¿]+; GREEK_TOKEN: [α-ω]+; RUSSIAN_TOKEN: [а-я]+; WS: [ ]+ -> skip; ``` -------------------------------- ### ANTLR Parser Start Rule Source: https://github.com/antlr/antlr4/blob/dev/runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserExec/Keyword_6.txt Specifies the starting rule for the ANTLR parser, which is 'program' in this case. ```antlr program ``` -------------------------------- ### Lexer Input and Output Example Source: https://github.com/antlr/antlr4/blob/dev/runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LexerErrors/StringsEmbeddedInActions_1.txt Provides a sample input string and the expected lexer output. This demonstrates how the defined grammar parses the input, identifying the string literal and the end of the file. ```text Input: ["foo"] Output: [@0,0:6='["foo"]',<1>,1:0] [@1,7:6='',<-1>,1:7] ``` -------------------------------- ### Parse with Sample Grammar (GUI) Source: https://github.com/antlr/antlr4/blob/dev/doc/getting-started.md Launch the ANTLR GUI tool to visualize the parse tree for a given grammar and input. Use ^D (Unix) or ^Z (Windows) to signal end of input. ```bash antlr4-parse Expr.g4 prog -gui 10+20*30 ^D ``` -------------------------------- ### ANTLR Parser Start Rule Source: https://github.com/antlr/antlr4/blob/dev/runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/DirectCallToLeftRecursiveRule_1.txt Specifies the starting rule for the ANTLR grammar, which is 'a' in this test case. ```antlr a ``` -------------------------------- ### Install antlr4-tools Source: https://github.com/antlr/antlr4/blob/dev/doc/getting-started.md Install the antlr4-tools package using pip. This provides command-line executables for ANTLR. ```bash pip install antlr4-tools ``` -------------------------------- ### Build and Execute Application with Maven Source: https://github.com/antlr/antlr4/blob/dev/doc/java-target.md This sequence of Maven commands first installs the project artifacts and then executes the main class of the application. This is an alternative to building a standalone JAR and executing it directly with `java`. ```bash mvn install mvn exec:java -Dexec.mainClass=org.abcd.examples.ArrayInit.ArrayInit {1,2,3} ^D ``` -------------------------------- ### Configure Maven Settings for Authentication Source: https://github.com/antlr/antlr4/wiki/Deploying-ANTLR-mvn-artifacts Set up authentication in `~/.m2/settings.xml` to allow deployment to the Sonatype repository. Ensure the server ID matches the one used in the deploy command. ```bash $ vi settings.xml ossrh parrt #### ``` -------------------------------- ### Include GNU Install Directories Source: https://github.com/antlr/antlr4/blob/dev/runtime/Cpp/CMakeLists.txt Includes the GNUInstallDirs module to define standard installation directory variables. ```cmake include(GNUInstallDirs) ``` -------------------------------- ### View Build Log Source: https://github.com/antlr/antlr4/wiki/How-to-build-ANTLR-itself Display the beginning of the bild.log file to inspect the commands executed during the build process. ```bash /tmp/antlr4 $ head bild.log [01/13/15 18:56:16 ./bild.py:39 bilder.py:107] platform=darwin [01/13/15 18:56:16 ./bild.py:39 bilder.py:108] jdk={'1.6': '/System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home', '1.7': '/Library/Java/JavaVirtualMachines/jdk1.7.0_51.jdk/Contents/Home', '1.8': '/Library/Java/JavaVirtualMachines/jdk1.8.0_25.jdk/Contents/Home'} [01/13/15 18:56:16] require parsers [01/13/15 18:56:16 require ./bild.py:74 bilder.py:370] require parsers [01/13/15 18:56:16 antlr3 ./bild.py:67 bilder.py:402] java -cp /Users/parrt/.bild/jars/antlr-3.5.1-complete.jar org.antlr.Tool -o /private/tmp/antlr4/gen3/org/antlr/v4/parse /private/tmp/antlr4/tool/src/org/antlr/v4/parse/GrammarTreeVisitor.g /private/tmp/antlr4/tool/src/org/antlr/v4/parse/BlockSetTransformer.g /private/tmp/antlr4/tool/src/org/antlr/v4/parse/LeftRecursiveRuleWalker.g /private/tmp/antlr4/tool/src/org/antlr/v4/parse/ANTLRLexer.g /private/tmp/antlr4/tool/src/org/antlr/v4/parse/ANTLRParser.g /private/tmp/antlr4/tool/src/org/antlr/v4/parse/ATNBuilder.g /private/tmp/antlr4/tool/src/org/antlr/v4/parse/ActionSplitter.g [01/13/15 18:56:19 antlr3 ./bild.py:69 bilder.py:402] java -cp /Users/parrt/.bild/jars/antlr-3.5.1-complete.jar org.antlr.Tool -o /private/tmp/antlr4/gen3/org/antlr/v4/codegen -lib /private/tmp/antlr4/gen3/org/antlr/v4/parse /private/tmp/antlr4/tool/src/org/antlr/v4/parse/SourceGenTriggers.g [01/13/15 18:56:20 antlr4 ./bild.py:71 bilder.py:423] java -cp /Users/parrt/.bild/jars/antlr-4.4-complete.jar org.antlr.v4.Tool -o /private/tmp/antlr4/gen4/org/antlr/v4/runtime/tree/xpath -package org.antlr.v4.runtime.tree.xpath /private/tmp/antlr4/runtime/Java/src/org/antlr/v4/runtime/tree/xpath/XPathLexer.g4 [01/13/15 18:56:20] build compile [01/13/15 18:56:20 require ./bild.py:74 bilder.py:378] build compile [01/13/15 18:56:20 javac ./bild.py:81 bilder.py:452] javac -version ... ``` -------------------------------- ### C++ Example: Setting up and using ANTLR4 Lexer and Parser Interpreters Source: https://github.com/antlr/antlr4/blob/dev/doc/interpreters.md This C++ code demonstrates how to load interpreter data files, initialize `LexerInterpreter` and `ParserInterpreter`, and parse an input string to generate a parse tree. It requires pre-generated `.interp` files for both the lexer and parser. ```cpp /** * sourceFileName - name of the file with content to parse * lexerName - the name of your lexer (arbitrary, that's what is used in error messages) * parserName - ditto for the parser * lexerDataFileName - the lexer interpeter data file name (e.g. `/ExprLexer.interp`) * parserDataFileName - ditto for the parser (e.g. `/Expr.interp`) * startRule - the name of the rule to start parsing at */ void parse(std::string const& sourceFileName, std::string const& lexerName, std::string const& parserName, std::string const& lexerDataFileName, std::string const& parserDataFileName, std::string const& startRule) { InterpreterData lexerData = InterpreterDataReader::parseFile(lexerDataFileName); InterpreterData parserData = InterpreterDataReader::parseFile(parserDataFileName); ANTLRFileStream input(sourceFileName); LexerInterpreter lexEngine(lexerName, lexerData.vocabulary, lexerData.ruleNames, lexerData.channels, lexerData.modes, lexerData.atn, &input); CommonTokenStream tokens(&lexEngine); /* Remove comment to print the tokens. tokens.fill(); std::cout << "INPUT:" << std::endl; for (auto token : tokens.getTokens()) { std::cout << token->toString() << std::endl; } */ ParserInterpreter parser(parserName, parserData.vocabulary, parserData.ruleNames, parserData.atn, &tokens); tree::ParseTree *tree = parser.parse(parser.getRuleIndex(startRule)); std::cout << "parse tree: " << tree->toStringTree(&parser) << std::endl; } ``` -------------------------------- ### Lexer Input and Output Example Source: https://github.com/antlr/antlr4/blob/dev/runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LexerErrors/InvalidCharInTokenAfterDFACache.txt Shows the input string 'abax' processed by the lexer. The expected output demonstrates successful tokenization of 'ab' and subsequent error handling for the invalid sequence 'ax'. ```text abax ``` ```text [@0,0:1='ab',<1>,1:0] [@1,4:3='',<-1>,1:4] ``` -------------------------------- ### ANTLR Start Rule Source: https://github.com/antlr/antlr4/blob/dev/runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserExec/Optional_3.txt Specifies the starting rule for the ANTLR parser. In this case, the parser will begin by attempting to match the 'stat' rule. ```text stat ``` -------------------------------- ### Input and Output for Unpredicated Path Example Source: https://github.com/antlr/antlr4/blob/dev/runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/SemPredEvalParser/UnpredicatedPathsInAlt.txt Provides the input 'x 4' and the expected output 'alt 1' when the semantic predicate in the grammar allows the first alternative to be chosen. This demonstrates a scenario where the predicate evaluates to true. ```text Input: x 4 Output: """alt 1 """ ``` -------------------------------- ### Start Rule for Grammar Source: https://github.com/antlr/antlr4/blob/dev/runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/ParserExec/Optional_1.txt Specifies the 'stat' rule as the starting point for parsing in the ANTLR grammar. This defines the entry point for the parser. ```antlr stat ``` -------------------------------- ### Grammar Start Rule Source: https://github.com/antlr/antlr4/blob/dev/runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/AmbigLR_1.txt Specifies the starting rule for the parser, 'prog', which is the entry point for parsing input according to the defined grammar. ```antlr prog ``` -------------------------------- ### Deploy ANTLR Python 2 Runtime Source: https://github.com/antlr/antlr4/wiki/Cutting-an-ANTLR-4-release Registers and uploads the ANTLR Python 2 runtime to PyPI using setup.py. ```bash cd ~/antlr/code/antlr4/runtime/Python2 # assume you have ~/.pypirc set up python setup.py register -r pypi python setup.py sdist bdist_wininst upload -r pypi ``` -------------------------------- ### Install Node.js and Mono on macOS Source: https://github.com/antlr/antlr4/wiki/How-to-build-ANTLR-itself Installs Node.js and Mono using Homebrew on macOS. These are required for running ANTLR tests on certain targets. ```bash brew install mono brew install node ``` -------------------------------- ### Publish C# Runtime to NuGet via Command Line Source: https://github.com/antlr/antlr4/blob/dev/doc/releasing-antlr.md Publishes the C# ANTLR runtime NuGet package using the 'nuget push' command. Requires a NuGet API key and ownership of the package. ```cmd cd bin/Release nuget push Antlr4.Runtime.Standard..nupkg -Source https://www.nuget.org/api/v2/package ``` -------------------------------- ### ANTLR Tree XPath Notation Examples Source: https://github.com/antlr/antlr4/blob/dev/CHANGES.txt Examples of XPath expressions used for navigating and selecting nodes within an ANTLR parse tree. ```XPath /prog/func ``` ```XPath /prog/* ``` ```XPath /*/func ``` ```XPath prog ``` ```XPath /prog ``` ```XPath /* ``` ```XPath *- ``` ```XPath //ID ``` ```XPath //expr/primary/ID ``` ```XPath //body//ID ``` ```XPath //'return' ``` ```XPath //primary/* ``` ```XPath //func/*/stat ``` ```XPath /prog/func/'def' ``` ```XPath //stat/';' ``` ```XPath //expr/primary/!ID ``` ```XPath //expr/!primary ``` ```XPath //!* ``` ```XPath /!* ``` -------------------------------- ### Build and Test Imported Grammar Source: https://github.com/antlr/antlr4/blob/dev/doc/grammars.md Demonstrates the command-line process to generate Java code from a grammar with imports, compile it, and then use the 'grun' tool to test a rule with sample input, showing how overridden rules and error handling function. ```bash $ antlr4 MyELang.g4 $ javac MyELang*.java $ grun MyELang stat => 34; => a; => ; => EOF <= line 3:0 extraneous input ';' expecting {INT, ID} ``` -------------------------------- ### Example Input and Output Source: https://github.com/antlr/antlr4/blob/dev/runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/Declarations_7.txt Provides a sample input string and its corresponding parse tree output generated by the ANTLR grammar. This illustrates how the left-recursive grammar parses the input. ```text [input] a[]() [output] """(s (declarator (declarator (declarator a) [ ]) ( )) ) """ ``` -------------------------------- ### Deploy ANTLR Python 3 Runtime Source: https://github.com/antlr/antlr4/wiki/Cutting-an-ANTLR-4-release Registers and uploads the ANTLR Python 3 runtime to PyPI using setup.py. ```bash cd ~/antlr/code/antlr4/runtime/Python3 # assume you have ~/.pypirc set up python setup.py register -r pypi python setup.py sdist bdist_wininst upload -r pypi ``` -------------------------------- ### Install ANTLR4 PHP Runtime Source: https://github.com/antlr/antlr4/blob/dev/doc/php-target.md Install the ANTLR4 PHP runtime using Composer. This command adds the necessary libraries to your project for running ANTLR-generated parsers. ```bash composer require antlr/antlr4-php-runtime ``` -------------------------------- ### Create and Run a Custom Listener in C++ Source: https://github.com/antlr/antlr4/blob/dev/doc/cpp-target.md Demonstrates how to create a custom listener by inheriting from the generated base listener. Use this to implement specific actions for parser rules. Assumes a grammar with a 'key' rule. ```cpp #include #include "antlr4-runtime.h" #include "MyGrammarLexer.h" #include "MyGrammarParser.h" #include "MyGrammarBaseListener.h" using namespace antlr4; class TreeShapeListener : public MyGrammarBaseListener { public: void enterKey(ParserRuleContext *ctx) override { // Do something when entering the key rule. } }; int main(int argc, const char* argv[]) { std::ifstream stream; stream.open(argv[1]); ANTLRInputStream input(stream); MyGrammarLexer lexer(&input); CommonTokenStream tokens(&lexer); MyGrammarParser parser(&tokens); tree::ParseTree *tree = parser.key(); TreeShapeListener listener; tree::ParseTreeWalker::DEFAULT.walk(&listener, tree); return 0; } ``` -------------------------------- ### Optional Subrule Example Source: https://github.com/antlr/antlr4/blob/dev/doc/parser-rules.md This example demonstrates an optional subrule, which can match zero or one occurrence of its alternatives. It's used for elements that may or may not be present. ```ANTLR classDeclaration : 'class' ID (typeParameters)? ('extends' type)? ('implements' typeList)? classBody ; ``` -------------------------------- ### Lexer Grammar with Invalid Start Character Source: https://github.com/antlr/antlr4/blob/dev/runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LexerErrors/InvalidCharAtStart.txt This lexer grammar defines a rule 'A' that expects 'a' followed by 'b'. When the input starts with 'x', a token recognition error occurs. ```antlr lexer grammar L; A : 'a' 'b' ; ``` -------------------------------- ### Build and Publish JavaScript Runtime to npm Source: https://github.com/antlr/antlr4/blob/dev/doc/releasing-antlr.md Steps to build the JavaScript ANTLR runtime and publish it to npm. Ensure you are in the correct directory and have run npm login. ```bash cd ~/antlr/code/antlr4/runtime/JavaScript rm -rf node_modules # seems we might need this later but try it here npm update npm install npm run build npm login # asks for username/password/2FA (npmjs.com) npm publish # don't put antlr4 on there or it will try to push the old version for some reason ``` -------------------------------- ### Input Example for Java Expressions Source: https://github.com/antlr/antlr4/blob/dev/runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/LeftRecursion/JavaExpressions_12.txt This is an example input string that conforms to the defined Java expressions grammar. It demonstrates the parsing of a complex array instantiation with arithmetic operations. ```input new T[((n-1) * x) + 1] ``` -------------------------------- ### Replace and Rename Main Java Program Source: https://github.com/antlr/antlr4/blob/dev/doc/java-target.md Remove the default Maven App.java and copy the book's Test.java, renaming it to ArrayInit.java. ```bash # Remove the maven file rm ./src/main/java/org/abcd/examples/ArrayInit/App.java # Copy and rename the example from the book cp ~/Downloads/code/starter/Test.java ./src/main/java/org/abcd/examples/ArrayInit/ArrayInit.java ``` -------------------------------- ### Lexer Keywords Map Example Source: https://github.com/antlr/antlr4/blob/dev/doc/grammars.md An example of a lexer's member section that uses a map to assign token types to keywords, demonstrating how to handle keywords explicitly. ```Java // keywords map used in lexer to assign token types Map keywords = new HashMap() {{ put("begin", KeywordsParser.BEGIN); put("end", KeywordsParser.END); ... }}; ``` -------------------------------- ### ANTLR Grammar Start Rule and Input Source: https://github.com/antlr/antlr4/blob/dev/runtime-testsuite/resources/org/antlr/v4/test/runtime/descriptors/Sets/UnicodeUnescapedBMPSet.txt Specifies the starting rule 'a' for the grammar and provides the input string 'aäあ亜c' to test the lexer's handling of the unescaped Unicode characters. ```antlr [start] a [input] aäあ亜c ``` -------------------------------- ### Install ANTLR Artifacts to Local Maven Repository Source: https://github.com/antlr/antlr4/blob/dev/doc/building-antlr.md Install the ANTLR artifacts into your local Maven repository without running tests. This makes the built JARs available for other projects. ```bash export MAVEN_OPTS="-Xmx1G" # don't forget this on linux $ mvn install -DskipTests # make sure all artifacts are visible on this machine ``` -------------------------------- ### Initialize Go Module Project Source: https://github.com/antlr/antlr4/blob/dev/doc/go-target.md Initialize a new Go module for your project before adding ANTLR4 runtime dependencies. ```bash $ cd mymodproject $ go mod init mymodproject ``` -------------------------------- ### Install ANTLR 4 Runtime Artifact to .m2 Source: https://github.com/antlr/antlr4/wiki/Deploying-ANTLR-mvn-artifacts Use this command to install the ANTLR 4 runtime JAR into your local Maven repository. This is necessary for applications that use the ANTLR runtime. ```bash $ mvn install:install-file \ -Dfile=/Users/parrt/antlr/code/antlr4/dist/antlr4-4.5-SNAPSHOT.jar \ -Dversion=4.5-SNAPSHOT \ -DgeneratePom=true \ -DgroupId=org.antlr \ -DartifactId=antlr4-runtime \ -Dpackaging=jar ``` -------------------------------- ### Run ANTLR Website Deployment Script Source: https://github.com/antlr/antlr4/blob/dev/doc/releasing-antlr.md Execute the deployment script to copy Javadoc and JAR files to the website. Provide the old and new ANTLR versions as arguments. ```bash cd ~/antlr/code/antlr4 python scripts/deploy_to_website.py 4.13.1 4.13.2 ``` -------------------------------- ### Go Generate Configuration Source: https://github.com/antlr/antlr4/blob/dev/doc/go-target.md Configure `go generate` for your project by creating `generate.go` and `generate.sh` files. Ensure grammar files are in a dedicated package and the package statement in the grammar reflects the Go package. ```golang package parser //go:generate ./generate.sh ``` -------------------------------- ### Get Parse Tree Subtree Text Source: https://github.com/antlr/antlr4/blob/dev/doc/faq/parse-trees.md Use the `getText(RuleContext)` method from `TokenStream` to get the combined text of all tokens in a subtree. This is generally preferred over the `ParseTree.getText()` method for including all tokens. ```java /** Return the combined text of all leaf nodes. Does not get any * off-channel tokens (if any) so won't return whitespace and * comments if they are sent to parser on hidden channel. */ String getText(); ``` ```java /** * Return the text of all tokens in the source interval of the specified * context. This method behaves like the following code, including potential * exceptions from the call to {@link #getText(Interval)}, but may be * optimized by the specific implementation. * *

If {@code ctx.getSourceInterval()} does not return a valid interval of * tokens provided by this stream, the behavior is unspecified.

* *
 * TokenStream stream = ...;
 * String text = stream.getText(ctx.getSourceInterval());
 * 
* * @param ctx The context providing the source interval of tokens to get * text for. * @return The text of all tokens within the source interval of {@code ctx}. */ public String getText(RuleContext ctx); ``` ```java mytokens.getText(mySubTree); ``` -------------------------------- ### Example of a left-recursive grammar accepted by ANTLR v4 Source: https://github.com/antlr/antlr4/blob/dev/doc/faq/general.md ANTLR v4 can accept left-recursive grammars, which are translated internally to a non-left recursive version. This example demonstrates a simple arithmetic expression grammar. ```antlr e : e '*' e | e '+' e | INT ; ``` -------------------------------- ### List Downloaded JARs Source: https://github.com/antlr/antlr4/wiki/How-to-build-ANTLR-itself View the contents of the ~/.bild/jars/ directory to see the ANTLR and related JAR files downloaded by the build script. ```bash $ ls ~/.bild/jars/ ST-4.0.8.jar antlr-4.5-SNAPSHOT-complete.jar bild-junit.jar antlr-3.5.1-complete.jar antlr-4.5-complete.jar hhamcrest-core-1.3.jar antlr-3.5.1-runtime.jar antlr-4.5-rc-1-complete.jar junit-4.11.jar antlr-4.4-complete.jar antlr4-4.5-complete.jar ``` -------------------------------- ### Install ANTLR Runtime Package Source: https://github.com/antlr/antlr4/blob/dev/runtime/CSharp/src/README.md Install the ANTLR 4 standard runtime for C# using the NuGet Package Manager Console. This package is required for your C# application to use the generated ANTLR code. ```powershell Install-Package Antlr4.Runtime.Standard ``` -------------------------------- ### Add Runtime and Demo Subdirectories Source: https://github.com/antlr/antlr4/blob/dev/runtime/Cpp/CMakeLists.txt Includes the 'runtime' subdirectory and conditionally includes the 'demo' subdirectory if the WITH_DEMO option is enabled. ```cmake add_subdirectory(runtime) if(WITH_DEMO) add_subdirectory(demo) endif(WITH_DEMO) ``` -------------------------------- ### Install ANTLR 4 Master Artifact to .m2 Source: https://github.com/antlr/antlr4/wiki/Deploying-ANTLR-mvn-artifacts Use this command to install the ANTLR 4 master artifact (complete JAR) into your local Maven repository. Ensure the file path to the JAR is correct. ```bash $ rm -rf ~/.m2/repository/org/antlr/antlr4* $ cd /tmp $ mvn install:install-file \ -Dfile=/Users/parrt/antlr/code/antlr4/dist/antlr4-4.5-SNAPSHOT-complete.jar \ -Dversion=4.5-SNAPSHOT \ -DgeneratePom=true \ -DgroupId=org.antlr \ -DartifactId=antlr4-master \ -Dpackaging=jar ``` -------------------------------- ### Build and Deploy C++ Runtime from Source on Linux/macOS Source: https://github.com/antlr/antlr4/blob/dev/doc/releasing-antlr.md This script builds the C++ runtime from source code, suitable for Linux and macOS. It generates a zip archive for distribution. ```bash cd ~/antlr/code/antlr4/runtime/Cpp ./deploy-source.sh cp antlr4-cpp-runtime-source.zip ~/antlr/sites/website-antlr4/download/antlr4-cpp-runtime-4.13.2-source.zip ```